Remove all legacy code from security-server
authorBartlomiej Grzelewski <b.grzelewski@samsung.com>
Tue, 5 Nov 2013 12:36:20 +0000 (13:36 +0100)
committerBartlomiej Grzelewski <b.grzelewski@samsung.com>
Thu, 6 Feb 2014 16:13:23 +0000 (17:13 +0100)
[Issue#]   SSDWSSP-424
[Bug]      N/A
[Problem]  Old code was not immune for interupts and have many
           synchronization issues.
[Solution] N/A

[Verification] Build, run tests.

Conflicts:

src/communication/security-server-comm.c
src/include/security-server-comm.h
src/server/main/security-server-util.cpp

Change-Id: Ifc091f4dd8994b53c76f90898e5d39ec2c12547a

175 files changed:
src/CMakeLists.txt
src/communication/security-server-comm.c [deleted file]
src/include/SLP_security-model_PG.h [deleted file]
src/include/SLP_security-server_PG.h [deleted file]
src/include/security-server-comm.h [deleted file]
src/include/security-server-common.h [deleted file]
src/include/security-server-util.h [deleted file]
src/include/smack-check.h [deleted file]
src/server/CMakeLists.txt [new file with mode: 0644]
src/server/client/client-app-permissions.cpp [new file with mode: 0644]
src/server/client/client-common.cpp [new file with mode: 0644]
src/server/client/client-common.h [new file with mode: 0644]
src/server/client/client-cookie.cpp [new file with mode: 0644]
src/server/client/client-get-gid.cpp [new file with mode: 0644]
src/server/client/client-get-object-name.cpp [new file with mode: 0644]
src/server/client/client-open-for.cpp [new file with mode: 0644]
src/server/client/client-password.cpp [new file with mode: 0644]
src/server/client/client-privilege-by-pid.cpp [new file with mode: 0644]
src/server/client/client-shared-memory.cpp [new file with mode: 0644]
src/server/client/client-socket-privilege.cpp [new file with mode: 0644]
src/server/common/connection-info.h [new file with mode: 0644]
src/server/common/message-buffer.cpp [new file with mode: 0644]
src/server/common/message-buffer.h [new file with mode: 0644]
src/server/common/protocols.cpp [new file with mode: 0644]
src/server/common/protocols.h [new file with mode: 0644]
src/server/common/smack-check.cpp [new file with mode: 0644]
src/server/common/smack-check.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/assert.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/binary_queue.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/colors.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/exception.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/noncopyable.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/noreturn.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/serialization.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/singleton.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/singleton_impl.h [new file with mode: 0644]
src/server/dpl/core/include/dpl/singleton_safe_impl.h [new file with mode: 0644]
src/server/dpl/core/src/assert.cpp [new file with mode: 0644]
src/server/dpl/core/src/binary_queue.cpp [new file with mode: 0644]
src/server/dpl/core/src/colors.cpp [new file with mode: 0644]
src/server/dpl/core/src/exception.cpp [new file with mode: 0644]
src/server/dpl/core/src/noncopyable.cpp [new file with mode: 0644]
src/server/dpl/core/src/serialization.cpp [new file with mode: 0644]
src/server/dpl/core/src/singleton.cpp [new file with mode: 0644]
src/server/dpl/log/include/dpl/log/abstract_log_provider.h [new file with mode: 0644]
src/server/dpl/log/include/dpl/log/audit-smack-log.h [new file with mode: 0644]
src/server/dpl/log/include/dpl/log/dlog_log_provider.h [new file with mode: 0644]
src/server/dpl/log/include/dpl/log/log.h [new file with mode: 0644]
src/server/dpl/log/include/dpl/log/old_style_log_provider.h [new file with mode: 0644]
src/server/dpl/log/src/abstract_log_provider.cpp [new file with mode: 0644]
src/server/dpl/log/src/audit-smack-log.cpp [new file with mode: 0644]
src/server/dpl/log/src/dlog_log_provider.cpp [new file with mode: 0644]
src/server/dpl/log/src/log.cpp [new file with mode: 0644]
src/server/dpl/log/src/old_style_log_provider.cpp [new file with mode: 0644]
src/server/main/generic-event.h [new file with mode: 0644]
src/server/main/generic-socket-manager.cpp [new file with mode: 0644]
src/server/main/generic-socket-manager.h [new file with mode: 0644]
src/server/main/security-server-util.cpp [new file with mode: 0644]
src/server/main/security-server-util.h [new file with mode: 0644]
src/server/main/server2-main.cpp [new file with mode: 0644]
src/server/main/server2-main.h [new file with mode: 0644]
src/server/main/service-thread.h [new file with mode: 0644]
src/server/main/socket-manager.cpp [new file with mode: 0644]
src/server/main/socket-manager.h [new file with mode: 0644]
src/server/security-server-main.c [deleted file]
src/server/service/app-permissions.cpp [new file with mode: 0644]
src/server/service/app-permissions.h [new file with mode: 0644]
src/server/service/cookie-jar.cpp [new file with mode: 0644]
src/server/service/cookie-jar.h [new file with mode: 0644]
src/server/service/cookie.cpp [new file with mode: 0644]
src/server/service/cookie.h [new file with mode: 0644]
src/server/service/data-share.cpp [new file with mode: 0644]
src/server/service/data-share.h [new file with mode: 0644]
src/server/service/get-gid.cpp [new file with mode: 0644]
src/server/service/get-gid.h [new file with mode: 0644]
src/server/service/get-object-name.cpp [new file with mode: 0644]
src/server/service/get-object-name.h [new file with mode: 0644]
src/server/service/open-for-manager.cpp [new file with mode: 0644]
src/server/service/open-for-manager.h [new file with mode: 0644]
src/server/service/open-for.cpp [new file with mode: 0644]
src/server/service/open-for.h [new file with mode: 0644]
src/server/service/password-exception.h [new file with mode: 0644]
src/server/service/password-file-buffer.cpp [new file with mode: 0644]
src/server/service/password-file-buffer.h [new file with mode: 0644]
src/server/service/password-file.cpp [new file with mode: 0644]
src/server/service/password-file.h [new file with mode: 0644]
src/server/service/password-manager.cpp [new file with mode: 0644]
src/server/service/password-manager.h [new file with mode: 0644]
src/server/service/password.cpp [new file with mode: 0644]
src/server/service/password.h [new file with mode: 0644]
src/server/service/privilege-by-pid.cpp [new file with mode: 0644]
src/server/service/privilege-by-pid.h [new file with mode: 0644]
src/server2/CMakeLists.txt [deleted file]
src/server2/client/client-app-permissions.cpp [deleted file]
src/server2/client/client-common.cpp [deleted file]
src/server2/client/client-common.h [deleted file]
src/server2/client/client-cookie.cpp [deleted file]
src/server2/client/client-get-gid.cpp [deleted file]
src/server2/client/client-get-object-name.cpp [deleted file]
src/server2/client/client-open-for.cpp [deleted file]
src/server2/client/client-password.cpp [deleted file]
src/server2/client/client-privilege-by-pid.cpp [deleted file]
src/server2/client/client-shared-memory.cpp [deleted file]
src/server2/client/client-socket-privilege.cpp [deleted file]
src/server2/common/connection-info.h [deleted file]
src/server2/common/message-buffer.cpp [deleted file]
src/server2/common/message-buffer.h [deleted file]
src/server2/common/protocols.cpp [deleted file]
src/server2/common/protocols.h [deleted file]
src/server2/dpl/core/include/dpl/assert.h [deleted file]
src/server2/dpl/core/include/dpl/binary_queue.h [deleted file]
src/server2/dpl/core/include/dpl/colors.h [deleted file]
src/server2/dpl/core/include/dpl/exception.h [deleted file]
src/server2/dpl/core/include/dpl/noncopyable.h [deleted file]
src/server2/dpl/core/include/dpl/noreturn.h [deleted file]
src/server2/dpl/core/include/dpl/serialization.h [deleted file]
src/server2/dpl/core/include/dpl/singleton.h [deleted file]
src/server2/dpl/core/include/dpl/singleton_impl.h [deleted file]
src/server2/dpl/core/include/dpl/singleton_safe_impl.h [deleted file]
src/server2/dpl/core/src/assert.cpp [deleted file]
src/server2/dpl/core/src/binary_queue.cpp [deleted file]
src/server2/dpl/core/src/colors.cpp [deleted file]
src/server2/dpl/core/src/exception.cpp [deleted file]
src/server2/dpl/core/src/noncopyable.cpp [deleted file]
src/server2/dpl/core/src/serialization.cpp [deleted file]
src/server2/dpl/core/src/singleton.cpp [deleted file]
src/server2/dpl/log/include/dpl/log/abstract_log_provider.h [deleted file]
src/server2/dpl/log/include/dpl/log/audit-smack-log.h [deleted file]
src/server2/dpl/log/include/dpl/log/dlog_log_provider.h [deleted file]
src/server2/dpl/log/include/dpl/log/log.h [deleted file]
src/server2/dpl/log/include/dpl/log/old_style_log_provider.h [deleted file]
src/server2/dpl/log/src/abstract_log_provider.cpp [deleted file]
src/server2/dpl/log/src/audit-smack-log.cpp [deleted file]
src/server2/dpl/log/src/dlog_log_provider.cpp [deleted file]
src/server2/dpl/log/src/log.cpp [deleted file]
src/server2/dpl/log/src/old_style_log_provider.cpp [deleted file]
src/server2/main/generic-event.h [deleted file]
src/server2/main/generic-socket-manager.cpp [deleted file]
src/server2/main/generic-socket-manager.h [deleted file]
src/server2/main/server2-main.cpp [deleted file]
src/server2/main/server2-main.h [deleted file]
src/server2/main/service-thread.h [deleted file]
src/server2/main/socket-manager.cpp [deleted file]
src/server2/main/socket-manager.h [deleted file]
src/server2/service/app-permissions.cpp [deleted file]
src/server2/service/app-permissions.h [deleted file]
src/server2/service/cookie-jar.cpp [deleted file]
src/server2/service/cookie-jar.h [deleted file]
src/server2/service/cookie.cpp [deleted file]
src/server2/service/cookie.h [deleted file]
src/server2/service/data-share.cpp [deleted file]
src/server2/service/data-share.h [deleted file]
src/server2/service/echo.cpp [deleted file]
src/server2/service/echo.h [deleted file]
src/server2/service/get-gid.cpp [deleted file]
src/server2/service/get-gid.h [deleted file]
src/server2/service/get-object-name.cpp [deleted file]
src/server2/service/get-object-name.h [deleted file]
src/server2/service/open-for-manager.cpp [deleted file]
src/server2/service/open-for-manager.h [deleted file]
src/server2/service/open-for.cpp [deleted file]
src/server2/service/open-for.h [deleted file]
src/server2/service/password-exception.h [deleted file]
src/server2/service/password-file-buffer.cpp [deleted file]
src/server2/service/password-file-buffer.h [deleted file]
src/server2/service/password-file.cpp [deleted file]
src/server2/service/password-file.h [deleted file]
src/server2/service/password-manager.cpp [deleted file]
src/server2/service/password-manager.h [deleted file]
src/server2/service/password.cpp [deleted file]
src/server2/service/password.h [deleted file]
src/server2/service/privilege-by-pid.cpp [deleted file]
src/server2/service/privilege-by-pid.h [deleted file]
src/util/security-server-util-common.c [deleted file]
src/util/smack-check.c [deleted file]

index c347633dbfd4c6680fbef07d4d18aec91375185f..5a1b28239a4f71ca81b9b59655950b80db7aff3b 100644 (file)
@@ -8,18 +8,14 @@ PKG_CHECK_MODULES(SECURITY_SERVER_DEP
     )
 
 SET(SECURITY_SERVER_PATH ${PROJECT_SOURCE_DIR}/src)
-SET(SERVER2_PATH ${PROJECT_SOURCE_DIR}/src/server2)
+SET(SERVER2_PATH ${PROJECT_SOURCE_DIR}/src/server)
 
 SET(SECURITY_SERVER_SOURCES
-    ${SECURITY_SERVER_PATH}/communication/security-server-comm.c
-    ${SECURITY_SERVER_PATH}/server/security-server-main.c
-    ${SECURITY_SERVER_PATH}/util/security-server-util-common.c
-    ${SECURITY_SERVER_PATH}/util/smack-check.c
+    ${SERVER2_PATH}/main/security-server-util.cpp
     ${SERVER2_PATH}/main/generic-socket-manager.cpp
     ${SERVER2_PATH}/main/socket-manager.cpp
     ${SERVER2_PATH}/main/server2-main.cpp
     ${SERVER2_PATH}/service/data-share.cpp
-    ${SERVER2_PATH}/service/echo.cpp
     ${SERVER2_PATH}/service/get-gid.cpp
     ${SERVER2_PATH}/service/app-permissions.cpp
     ${SERVER2_PATH}/service/cookie.cpp
@@ -65,25 +61,23 @@ SET(SECURITY_CLIENT_VERSION_MAJOR 1)
 SET(SECURITY_CLIENT_VERSION ${SECURITY_CLIENT_VERSION_MAJOR}.0.1)
 
 INCLUDE_DIRECTORIES(
-    ${SECURITY_SERVER_PATH}/server2/client
-    ${SECURITY_SERVER_PATH}/server2/common
-    ${SECURITY_SERVER_PATH}/server2/dpl/core/include
-    ${SECURITY_SERVER_PATH}/server2/dpl/log/include
+    ${SERVER2_PATH}/client
+    ${SERVER2_PATH}/common
+    ${SERVER2_PATH}/dpl/core/include
+    ${SERVER2_PATH}/dpl/log/include
     )
 
 SET(SECURITY_CLIENT_SOURCES
-    ${SECURITY_SERVER_PATH}/server2/client/client-common.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-shared-memory.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-get-gid.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-app-permissions.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-cookie.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-privilege-by-pid.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-socket-privilege.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-get-object-name.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-open-for.cpp
-    ${SECURITY_SERVER_PATH}/server2/client/client-password.cpp
-    ${SECURITY_SERVER_PATH}/communication/security-server-comm.c
-    ${SECURITY_SERVER_PATH}/util/smack-check.c
+    ${SERVER2_PATH}/client/client-common.cpp
+    ${SERVER2_PATH}/client/client-shared-memory.cpp
+    ${SERVER2_PATH}/client/client-get-gid.cpp
+    ${SERVER2_PATH}/client/client-app-permissions.cpp
+    ${SERVER2_PATH}/client/client-cookie.cpp
+    ${SERVER2_PATH}/client/client-privilege-by-pid.cpp
+    ${SERVER2_PATH}/client/client-socket-privilege.cpp
+    ${SERVER2_PATH}/client/client-get-object-name.cpp
+    ${SERVER2_PATH}/client/client-open-for.cpp
+    ${SERVER2_PATH}/client/client-password.cpp
     )
 
 ADD_LIBRARY(${TARGET_SECURITY_CLIENT} SHARED ${SECURITY_CLIENT_SOURCES})
@@ -119,4 +113,4 @@ INSTALL(FILES
 
 ################################################################################
 
-ADD_SUBDIRECTORY(server2)
+ADD_SUBDIRECTORY(server)
diff --git a/src/communication/security-server-comm.c b/src/communication/security-server-comm.c
deleted file mode 100644 (file)
index 3b197e8..0000000
+++ /dev/null
@@ -1,1132 +0,0 @@
-/*
- * security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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
- *
- */
-
-#include <sys/poll.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/smack.h>
-#include <fcntl.h>
-#include <pwd.h>
-#include <sys/un.h>
-#include <errno.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <limits.h>
-#include <ctype.h>
-
-#include <systemd/sd-daemon.h>
-
-#include "security-server-common.h"
-#include "security-server-comm.h"
-#include "smack-check.h"
-
-void printhex(const unsigned char *data, int size)
-{
-    int i;
-    for (i = 0; i < size; i++)
-    {
-        if (data[i] < 0xF)
-            printf("0");
-
-        printf("%X ", data[i]);
-        if (((i + 1) % 16) == 0 && i != 0)
-            printf("\n");
-    }
-    printf("\n");
-}
-
-/* Return code in packet is positive integer *
- * We need to convert them to error code which are negative integer */
-int return_code_to_error_code(int ret_code)
-{
-    int ret;
-    switch (ret_code)
-    {
-        case SECURITY_SERVER_RETURN_CODE_SUCCESS:
-        case SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED:
-            ret = SECURITY_SERVER_SUCCESS;
-            break;
-        case SECURITY_SERVER_RETURN_CODE_BAD_REQUEST:
-            ret = SECURITY_SERVER_ERROR_BAD_REQUEST;
-            break;
-        case SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED:
-            ret = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-            break;
-        case SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED:
-            ret = SECURITY_SERVER_ERROR_ACCESS_DENIED;
-            break;
-        case SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT:
-            ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
-            break;
-        case SECURITY_SERVER_RETURN_CODE_SERVER_ERROR:
-            ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-            break;
-        case SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE:
-            ret = SECURITY_SERVER_ERROR_NO_SUCH_COOKIE;
-            break;
-        default:
-            ret = SECURITY_SERVER_ERROR_UNKNOWN;
-            break;
-    }
-    return ret;
-}
-
-int check_socket_poll(int sockfd, int event, int timeout)
-{
-    struct pollfd poll_fd[1];
-    int retval = SECURITY_SERVER_ERROR_POLL;
-
-    poll_fd[0].fd = sockfd;
-    poll_fd[0].events = event;
-    retval = poll(poll_fd, 1, timeout);
-    if (retval < 0)
-    {
-        SEC_SVR_ERR("poll() error. errno=%d", errno);
-        if (errno != EINTR)
-            return SECURITY_SERVER_ERROR_POLL;
-        else
-        {
-            /* Chile process has been closed. Not poll() problem. Call it once again */
-            return check_socket_poll(sockfd, event, timeout);
-        }
-    }
-
-    /* Timed out */
-    if (retval == 0)
-    {
-        return SECURITY_SERVER_ERROR_TIMEOUT;
-    }
-
-    if (poll_fd[0].revents != event)
-    {
-        SEC_SVR_ERR("Something wrong on the peer socket. event=0x%x", poll_fd[0].revents);
-        return SECURITY_SERVER_ERROR_POLL;
-    }
-    return SECURITY_SERVER_SUCCESS;
-}
-
-int safe_server_sock_close(int client_sockfd)
-{
-    struct pollfd poll_fd[1];
-    poll_fd[0].fd = client_sockfd;
-    poll_fd[0].events = POLLRDHUP;
-    if (0 > poll(poll_fd, 1, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND)) {
-        SECURE_SLOGE("%s", "Unable to poll from socket");
-        return SECURITY_SERVER_ERROR_SOCKET;
-    }
-    SEC_SVR_DBG("%s", "Server: Closing server socket");
-    close(client_sockfd);
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Get socket from systemd */
-int get_socket_from_systemd(int *sockfd)
-{
-    int n = sd_listen_fds(0);
-    int fd;
-
-    for(fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) {
-        if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1,
-                                  SECURITY_SERVER_SOCK_PATH, 0))
-        {
-            *sockfd = fd;
-            return SECURITY_SERVER_SUCCESS;
-        }
-    }
-    return SECURITY_SERVER_ERROR_SOCKET;
-}
-
-/* Create a Unix domain socket and bind */
-int create_new_socket(int *sockfd)
-{
-    int retval = 0, localsockfd = 0, flags;
-    struct sockaddr_un serveraddr;
-    mode_t sock_mode;
-
-    /* Deleted garbage Unix domain socket file */
-    retval = remove(SECURITY_SERVER_SOCK_PATH);
-
-    if (retval == -1 && errno != ENOENT) {
-        retval = SECURITY_SERVER_ERROR_UNKNOWN;
-        localsockfd = -1;
-        SECURE_SLOGE("%s", "Unable to remove /tmp/.security_server.sock");
-        goto error;
-    }
-
-    /* Create Unix domain socket */
-    if ((localsockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
-    {
-        retval = SECURITY_SERVER_ERROR_SOCKET;
-        localsockfd = -1;
-        SEC_SVR_ERR("%s", "Socket creation failed");
-        goto error;
-    }
-
-    // If SMACK is present we have to label our sockets regardless of SMACK_ENABLED flag
-    if (smack_runtime_check()) {
-        if (smack_fsetlabel(localsockfd, "@", SMACK_LABEL_IPOUT) != 0)
-        {
-            SEC_SVR_ERR("%s", "SMACK labeling failed");
-            if (errno != EOPNOTSUPP)
-            {
-                retval = SECURITY_SERVER_ERROR_SOCKET;
-                close(localsockfd);
-                localsockfd = -1;
-                goto error;
-            }
-        }
-        if (smack_fsetlabel(localsockfd, "*", SMACK_LABEL_IPIN) != 0)
-        {   SEC_SVR_ERR("%s", "SMACK labeling failed");
-            if (errno != EOPNOTSUPP)
-            {
-                retval = SECURITY_SERVER_ERROR_SOCKET;
-                close(localsockfd);
-                localsockfd = -1;
-                goto error;
-            }}
-    }
-    else {
-        SEC_SVR_DBG("SMACK is not available. Sockets won't be labeled.");
-    }
-
-    /* Make socket as non blocking */
-    if ((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
-        fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
-    {
-        retval = SECURITY_SERVER_ERROR_SOCKET;
-        close(localsockfd);
-        localsockfd = -1;
-        SEC_SVR_ERR("%s", "Cannot go to nonblocking mode");
-        goto error;
-    }
-
-    bzero (&serveraddr, sizeof(serveraddr));
-    serveraddr.sun_family = AF_UNIX;
-    strncpy(serveraddr.sun_path, SECURITY_SERVER_SOCK_PATH,
-        strlen(SECURITY_SERVER_SOCK_PATH));
-    serveraddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
-
-    /* Bind the socket */
-    if ((bind(localsockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr))) < 0)
-    {
-        retval = SECURITY_SERVER_ERROR_SOCKET_BIND;
-        SEC_SVR_ERR("%s", "Cannot bind");
-        close(localsockfd);
-        localsockfd = -1;
-        goto error;
-    }
-
-
-    /* Change permission to accept all processes that has different uID/gID */
-    sock_mode = (S_IRWXU | S_IRWXG | S_IRWXO);
-    /* Flawfinder hits this chmod function as level 5 CRITICAL as race condition flaw *
-     * Flawfinder recommends to user fchmod insted of chmod
-     * But, fchmod doesn't work on socket file so there is no other choice at this point */
-    if (chmod(SECURITY_SERVER_SOCK_PATH, sock_mode) < 0)     /* Flawfinder: ignore */
-    {
-        SEC_SVR_ERR("%s", "chmod() error");
-        retval = SECURITY_SERVER_ERROR_SOCKET;
-        close(localsockfd);
-        localsockfd = -1;
-        goto error;
-    }
-
-    retval = SECURITY_SERVER_SUCCESS;
-
-error:
-    *sockfd = localsockfd;
-    return retval;
-}
-
-/* Authenticate peer that it's really security server.
- * Check UID that is root
- */
-int authenticate_server(int sockfd)
-{
-    int retval;
-    struct ucred cr;
-    unsigned int cl = sizeof(cr);
-/*     char *exe = NULL;*/
-
-    /* get socket peer credential */
-    if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
-    {
-        retval = SECURITY_SERVER_ERROR_SOCKET;
-        SEC_SVR_ERR("%s", "getsockopt() failed");
-        goto error;
-    }
-
-    /* Security server must run as root */
-    if (cr.uid != 0)
-    {
-        retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-        SEC_SVR_ERR("Peer is not root: uid=%d", cr.uid);
-        goto error;
-    }
-    else
-        retval = SECURITY_SERVER_SUCCESS;
-
-    /* Read command line of the PID from proc fs */
-    /* This is commented out because non root process cannot read link of /proc/pid/exe */
-/*     exe = read_exe_path_from_proc(cr.pid);
-
-    if(strcmp(exe, SECURITY_SERVER_DAEMON_PATH) != 0)
-    {
-        retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-        SEC_SVR_DBG("Executable path is different. auth failed. Exe path=%s", exe);
-    }
-    else
-    {
-        retval = SECURITY_SERVER_SUCCESS;
-        SEC_SVR_DBG("Server authenticatd. %s, sockfd=%d", exe, sockfd);
-    }
-*/
-error:
-/*     if(exe != NULL)
-        free(exe);
-*/
-    return retval;
-}
-
-/* Create a socket and connect to Security Server */
-int connect_to_server(int *fd)
-{
-    struct sockaddr_un clientaddr;
-    int client_len = 0, localsockfd, ret, flags;
-    *fd = -1;
-
-    /* Create a socket */
-    localsockfd = socket(AF_UNIX, SOCK_STREAM, 0);
-    if (localsockfd < 0)
-    {
-        SEC_SVR_ERR("%s", "Error on socket()");
-        return SECURITY_SERVER_ERROR_SOCKET;
-    }
-
-    /* Make socket as non blocking */
-    if ((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
-        fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
-    {
-        close(localsockfd);
-        SEC_SVR_ERR("%s", "Cannot go to nonblocking mode");
-        return SECURITY_SERVER_ERROR_SOCKET;
-    }
-
-    bzero(&clientaddr, sizeof(clientaddr));
-    clientaddr.sun_family = AF_UNIX;
-    strncpy(clientaddr.sun_path, SECURITY_SERVER_SOCK_PATH, strlen(SECURITY_SERVER_SOCK_PATH));
-    clientaddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
-    client_len = sizeof(clientaddr);
-
-    ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
-    if (ret < 0)
-    {
-        if (errno == EINPROGRESS)
-        {
-            SEC_SVR_DBG("%s", "Connection is in progress");
-            ret = check_socket_poll(localsockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-            if (ret == SECURITY_SERVER_ERROR_POLL)
-            {
-                SEC_SVR_ERR("%s", "poll() error");
-                close(localsockfd);
-                return SECURITY_SERVER_ERROR_SOCKET;
-            }
-            if (ret == SECURITY_SERVER_ERROR_TIMEOUT)
-            {
-                SEC_SVR_ERR("%s", "poll() timeout");
-                close(localsockfd);
-                return SECURITY_SERVER_ERROR_SOCKET;
-            }
-            ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
-            if (ret < 0)
-            {
-                SEC_SVR_ERR("%s", "connection failed");
-                close(localsockfd);
-                return SECURITY_SERVER_ERROR_SOCKET;
-            }
-        }
-        else
-        {
-            SEC_SVR_ERR("%s", "Connection failed");
-            close(localsockfd);
-            return SECURITY_SERVER_ERROR_SOCKET;
-        }
-    }
-
-    /* Authenticate the peer is actually security server */
-    ret = authenticate_server(localsockfd);
-    if (ret != SECURITY_SERVER_SUCCESS)
-    {
-        close(localsockfd);
-        SEC_SVR_ERR("Authentication failed. %d", ret);
-        return ret;
-    }
-    *fd = localsockfd;
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Accept a new client connection */
-int accept_client(int server_sockfd)
-{
-    /* Call poll() to wait for socket connection */
-    int retval, localsockfd;
-    struct sockaddr_un clientaddr;
-    unsigned int client_len;
-
-    client_len = sizeof(clientaddr);
-
-    /* Check poll */
-    retval = check_socket_poll(server_sockfd, POLLIN, SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND);
-    if (retval == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "Error on polling");
-        return SECURITY_SERVER_ERROR_SOCKET;
-    }
-
-    /* Timed out */
-    if (retval == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        /*SEC_SVR_DBG("%s", "accept() timeout");*/
-        return SECURITY_SERVER_ERROR_TIMEOUT;
-    }
-
-    localsockfd = accept(server_sockfd,
-        (struct sockaddr*)&clientaddr,
-        &client_len);
-
-    if (localsockfd < 0)
-    {
-        SEC_SVR_ERR("Cannot accept client. errno=%d", errno);
-        return SECURITY_SERVER_ERROR_SOCKET;
-    }
-    return localsockfd;
-}
-
-/* Minimal check of request packet */
-int validate_header(basic_header hdr)
-{
-    if (hdr.version != SECURITY_SERVER_MSG_VERSION)
-        return SECURITY_SERVER_ERROR_BAD_REQUEST;
-
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send generic response packet to client
- *
- * Generic Response Packet Format
- 0                   1                   2                   3
- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
-|---------------------------------------------------------------|
-| version=0x01  |  Message ID   |Message Length (without header)|
-|---------------------------------------------------------------|
-|  return code  |
------------------
-*/
-int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code)
-{
-    response_header hdr;
-    int size;
-
-    /* Assemble header */
-    hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-    hdr.basic_hdr.msg_id = msgid;
-    hdr.basic_hdr.msg_len = 0;
-    hdr.return_code = return_code;
-
-    /* Check poll */
-    size = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (size == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "poll() error");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-    if (size == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "poll() timeout");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-
-    /* Send to client */
-    size = TEMP_FAILURE_RETRY(write(sockfd, &hdr, sizeof(hdr)));
-
-    if (size < (int)sizeof(hdr))
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    return SECURITY_SERVER_SUCCESS;
-}
-
-
-/* Send Object name response *
- * Get Object name response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x06 |       Message Length          |
- * |---------------------------------------------------------------|
- * |  return code  |                                               |
- * -----------------                                               |
- * |                 object name                                   |
- * |---------------------------------------------------------------|
-*/
-int send_object_name(int sockfd, char *obj)
-{
-    response_header hdr;
-    unsigned char msg[strlen(obj) + sizeof(hdr)];
-    int ret;
-
-    hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-    hdr.basic_hdr.msg_id = 0x06;
-    hdr.basic_hdr.msg_len = strlen(obj);
-    hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-
-    memcpy(msg, &hdr, sizeof(hdr));
-    memcpy(msg + sizeof(hdr), obj, strlen(obj));
-
-    /* Check poll */
-    ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (ret == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "poll() error");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-    if (ret == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "poll() timeout");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-
-    ret = TEMP_FAILURE_RETRY(write(sockfd, msg, sizeof(hdr) + strlen(obj)));
-    if (ret < (int)(sizeof(hdr) + strlen(obj)))
-    {
-        /* Error on writing */
-        SEC_SVR_ERR("Error on write: %d", ret);
-        ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-        return ret;
-    }
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send GID response to client
- *
- * Get GID response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x08 |       Message Length = 4      |
- * |---------------------------------------------------------------|
- * |  return code  |           gid (first 3 words)                 |
- * |---------------------------------------------------------------|
- * |gid(last word) |
- * |---------------|
-*/
-int send_gid(int sockfd, int gid)
-{
-    response_header hdr;
-    unsigned char msg[sizeof(gid) + sizeof(hdr)];
-    int ret;
-
-    /* Assemble header */
-    hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-    hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_RESPONSE;
-    hdr.basic_hdr.msg_len = sizeof(gid);
-    hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
-
-    /* Perpare packet */
-    memcpy(msg, &hdr, sizeof(hdr));
-    memcpy(msg + sizeof(hdr), &gid, sizeof(gid));
-
-    /* Check poll */
-    ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (ret == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "poll() error");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-    if (ret == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "poll() timeout");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-
-    /* Send it */
-    ret = TEMP_FAILURE_RETRY(write(sockfd, msg, sizeof(hdr) + sizeof(gid)));
-    if (ret < (int)(sizeof(hdr) + sizeof(gid)))
-    {
-        /* Error on writing */
-        SEC_SVR_ERR("Error on write(): %d", ret);
-        ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-        return ret;
-    }
-    return SECURITY_SERVER_SUCCESS;
-}
-
-
-/* Send Check password response to client
- *
- * Check password response packet format
- *  0                   1                   2                   3
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |   MessageID   |       Message Length = 12     |
- * |---------------------------------------------------------------|
- * |  return code  |           attempts (first 3 words)            |
- * |---------------------------------------------------------------|
- * |attempts(rest) |          max_attempts (first 3 words)         |
- * |---------------|-----------------------------------------------|
- * | max_attempts  |          expire_in_days (first 3 words)       |
- * |---------------------------------------------------------------|
- * |expire_in_days |
- * |----------------
- */
-int send_pwd_response(const int sockfd,
-                      const unsigned char msg_id,
-                      const unsigned char return_code,
-                      const unsigned int current_attempts,
-                      const unsigned int max_attempts,
-                      const unsigned int expire_time)
-{
-    response_header hdr;
-    unsigned int expire_secs;
-    unsigned char msg[sizeof(hdr) + sizeof(current_attempts) + sizeof(max_attempts) + sizeof(expire_secs)];
-    int ret, ptr = 0;
-
-
-    /* Assemble header */
-    hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
-    hdr.basic_hdr.msg_id = msg_id;
-    hdr.basic_hdr.msg_len = sizeof(unsigned int) * 3;
-    hdr.return_code = return_code;
-
-    /* Perpare packet */
-    memcpy(msg, &hdr, sizeof(hdr));
-    ptr += sizeof(hdr);
-    memcpy(msg + ptr, &current_attempts, sizeof(current_attempts));
-    ptr += sizeof(current_attempts);
-    memcpy(msg + ptr, &max_attempts, sizeof(max_attempts));
-    ptr += sizeof(max_attempts);
-    memcpy(msg + ptr, &expire_time, sizeof(expire_time));
-    ptr += sizeof(expire_time);
-
-    /* Check poll */
-    ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (ret == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "Server: poll() error");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-    if (ret == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "Server: poll() timeout");
-        return SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-
-    /* Send it */
-    ret = TEMP_FAILURE_RETRY(write(sockfd, msg, ptr));
-    if (ret < ptr)
-    {
-        /* Error on writing */
-        SEC_SVR_ERR("Server: ERROR on write(): %d", ret);
-        ret = SECURITY_SERVER_ERROR_SEND_FAILED;
-        return ret;
-    }
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Send GID request message to security server
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x07 |   Message Length = variable   |
- * |---------------------------------------------------------------|
- * |                                                               |
- * |                   Object name (variable)                      |
- * |                                                               |
- * |---------------------------------------------------------------|
- */
-int send_gid_request(int sock_fd, const char *object)
-{
-    basic_header hdr;
-    int retval = 0, send_len = 0;
-    unsigned char *buf = NULL;
-
-    if (strlen(object) > SECURITY_SERVER_MAX_OBJ_NAME)
-    {
-        /* Object name is too big*/
-        SEC_SVR_ERR("Object name is too big %dbytes", strlen(object));
-        return SECURITY_SERVER_ERROR_INPUT_PARAM;
-    }
-
-    hdr.version = SECURITY_SERVER_MSG_VERSION;
-    hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_REQUEST;
-    hdr.msg_len = strlen(object);
-
-    send_len = sizeof(hdr) + strlen(object);
-
-    buf = malloc(send_len);
-    if (buf == NULL)
-    {
-        SEC_SVR_ERR("%s", "out of memory");
-        return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-    }
-
-    memcpy(buf, &hdr, sizeof(hdr));
-    memcpy(buf + sizeof(hdr), object, strlen(object));
-
-    /* Check poll */
-    retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (retval == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "poll() error");
-        retval = SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-    }
-    if (retval == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "poll() timeout");
-        retval = SECURITY_SERVER_ERROR_SEND_FAILED;
-        goto error;
-    }
-
-    retval = TEMP_FAILURE_RETRY(write(sock_fd, buf, send_len));
-    if (retval < send_len)
-    {
-        /* Write error */
-        SEC_SVR_ERR("Error on write(): %d. errno=%d, sockfd=%d", retval, errno, sock_fd);
-        retval = SECURITY_SERVER_ERROR_SEND_FAILED;
-    }
-    else
-        retval = SECURITY_SERVER_SUCCESS;
-
-error:
-    if (buf != NULL)
-        free(buf);
-
-    return retval;
-}
-
-/* Send object name request message to security server *
- *
- * Message format
- *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- * |---------------------------------------------------------------|
- * | version=0x01  |MessageID=0x05 |       Message Length = 4      |
- * |---------------------------------------------------------------|
- * |                               gid                             |
- * |---------------------------------------------------------------|
- */
-// int send_object_name_request(int sock_fd, int gid)
-// {
-//     basic_header hdr;
-//     int retval;
-//     unsigned char buf[sizeof(hdr) + sizeof(gid)];
-
-//     /* Assemble header */
-//     hdr.version = SECURITY_SERVER_MSG_VERSION;
-//     hdr.msg_id = SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST;
-//     hdr.msg_len = sizeof(gid);
-
-//     memcpy(buf, &hdr, sizeof(hdr));
-//     memcpy(buf + sizeof(hdr), &gid, sizeof(gid));
-
-//     /* Check poll */
-//     retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-//     if (retval == SECURITY_SERVER_ERROR_POLL)
-//     {
-//         SEC_SVR_ERR("%s", "poll() error");
-//         return SECURITY_SERVER_ERROR_SEND_FAILED;
-//     }
-//     if (retval == SECURITY_SERVER_ERROR_TIMEOUT)
-//     {
-//         SEC_SVR_ERR("%s", "poll() timeout");
-//         return SECURITY_SERVER_ERROR_SEND_FAILED;
-//     }
-
-//     /* Send to server */
-//     retval = TEMP_FAILURE_RETRY(write(sock_fd, buf, sizeof(buf)));
-//     if (retval < sizeof(buf))
-//     {
-//         /* Write error */
-//         SEC_SVR_ERR("Error on write(): %d", retval);
-//         return SECURITY_SERVER_ERROR_SEND_FAILED;
-//     }
-//     return SECURITY_SERVER_SUCCESS;
-// }
-
-/* Receive request header */
-int recv_hdr(int client_sockfd, basic_header *basic_hdr)
-{
-    int retval;
-
-    /* Check poll */
-    retval = check_socket_poll(client_sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (retval == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "poll() error");
-        return SECURITY_SERVER_ERROR_SOCKET;
-    }
-    if (retval == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "poll() timeout");
-        return SECURITY_SERVER_ERROR_TIMEOUT;
-    }
-
-    /* Receive request header first */
-    retval = TEMP_FAILURE_RETRY(read(client_sockfd, basic_hdr, sizeof(basic_header)));
-    if (retval < (int)sizeof(basic_header))
-    {
-        SEC_SVR_ERR("read failed. closing socket %d", retval);
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-
-    /* Validate header */
-    retval = validate_header(*basic_hdr);
-    return retval;
-}
-
-int recv_generic_response(int sockfd, response_header *hdr)
-{
-    int retval;
-
-    /* Check poll */
-    retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (retval == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "Client: poll() error");
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-    if (retval == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "Client: poll() timeout");
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-
-    /* Receive response */
-    retval = TEMP_FAILURE_RETRY(read(sockfd, hdr, sizeof(response_header)));
-    if (retval < (int)sizeof(response_header))
-    {
-        /* Error on socket */
-        SEC_SVR_ERR("Client: Receive failed %d", retval);
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-
-    if (hdr->return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
-    {
-        /* Return codes
-         *   SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST
-         *   SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE
-         * are not errors but warnings
-         */
-        SEC_SVR_WRN("Client: return code is not success: %d", hdr->return_code);
-        return return_code_to_error_code(hdr->return_code);
-    }
-    return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_get_gid_response(int sockfd, response_header *hdr, int *gid)
-{
-    int retval;
-
-    retval = recv_generic_response(sockfd, hdr);
-    if (retval != SECURITY_SERVER_SUCCESS)
-        return return_code_to_error_code(hdr->return_code);
-
-    retval = TEMP_FAILURE_RETRY(read(sockfd, gid, sizeof(int)));
-    if (retval < (int)sizeof(int))
-    {
-        /* Error on socket */
-        SEC_SVR_ERR("Receive failed %d", retval);
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-    return SECURITY_SERVER_SUCCESS;
-}
-
-int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size)
-{
-    int retval;
-    char *local_obj_name = NULL;
-
-    /* Check poll */
-    retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
-    if (retval == SECURITY_SERVER_ERROR_POLL)
-    {
-        SEC_SVR_ERR("%s", "poll() error");
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-    if (retval == SECURITY_SERVER_ERROR_TIMEOUT)
-    {
-        SEC_SVR_ERR("%s", "poll() timeout");
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-
-    /* Read response */
-    retval = TEMP_FAILURE_RETRY(read(sockfd, hdr, sizeof(response_header)));
-    if (retval < (int)sizeof(response_header))
-    {
-        /* Error on socket */
-        SEC_SVR_ERR("cannot recv respons: %d", retval);
-        return SECURITY_SERVER_ERROR_RECV_FAILED;
-    }
-
-    if (hdr->return_code == SECURITY_SERVER_RETURN_CODE_SUCCESS)
-    {
-        if (max_object_size < hdr->basic_hdr.msg_len)
-        {
-            SEC_SVR_ERR("Object name is too small need %d bytes, but %d bytes", hdr->basic_hdr.msg_len, max_object_size);
-            return SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
-        }
-        if (hdr->basic_hdr.msg_len > SECURITY_SERVER_MAX_OBJ_NAME)
-        {
-            SEC_SVR_ERR("Received object name is too big. %d", hdr->basic_hdr.msg_len);
-            return SECURITY_SERVER_ERROR_BAD_RESPONSE;
-        }
-
-        local_obj_name = malloc(hdr->basic_hdr.msg_len + 1);
-        if (local_obj_name == NULL)
-        {
-            SEC_SVR_ERR("%s", "Out of memory error");
-            return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-        }
-
-        retval = TEMP_FAILURE_RETRY(read(sockfd, local_obj_name, hdr->basic_hdr.msg_len));
-        if (retval < (hdr->basic_hdr.msg_len))
-        {
-            /* Error on socket */
-            SEC_SVR_ERR("read() failed: %d", retval);
-            if (local_obj_name != NULL)
-                free(local_obj_name);
-            return SECURITY_SERVER_ERROR_RECV_FAILED;
-        }
-        memcpy(object, local_obj_name, hdr->basic_hdr.msg_len);
-        object[hdr->basic_hdr.msg_len] = 0;
-        retval = SECURITY_SERVER_SUCCESS;
-    }
-    else
-    {
-        SEC_SVR_ERR("Error received. return code: %d", hdr->return_code);
-        retval = return_code_to_error_code(hdr->return_code);
-        return retval;
-    }
-
-    if (local_obj_name != NULL)
-        free(local_obj_name);
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Authenticate client application *
- * Currently it only gets peer's credential information only *
- * If we need, we can extend in the futer */
-int authenticate_client_application(int sockfd, int *pid, int *uid)
-{
-    struct ucred cr;
-    unsigned int cl = sizeof(cr);
-
-    /* get PID of socket peer */
-    if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
-    {
-        SEC_SVR_ERR("%s", "getsockopt failed");
-        return SECURITY_SERVER_ERROR_SOCKET;
-    }
-    *pid = cr.pid;
-    *uid = cr.uid;
-    return SECURITY_SERVER_SUCCESS;
-}
-
-/* Authenticate the application is middleware daemon
- * The middleware must run as root (or middleware user) and the cmd line must be
- * pre listed for authentication to succeed */
-int authenticate_client_middleware(int sockfd, int *pid)
-{
-    int uid;
-    return authenticate_client_application(sockfd, pid, &uid);
-#if 0
-    int retval = SECURITY_SERVER_SUCCESS;
-    struct ucred cr;
-    unsigned int cl = sizeof(cr);
-    char *exe = NULL;
-    struct passwd pw, *ppw;
-    size_t buf_size;
-    char *buf;
-    static uid_t middleware_uid = 0;
-
-    *pid = 0;
-
-    /* get PID of socket peer */
-    if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
-    {
-        retval = SECURITY_SERVER_ERROR_SOCKET;
-        SEC_SVR_ERR("%s", "Error on getsockopt");
-        goto error;
-    }
-
-    if (!middleware_uid)
-    {
-        buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
-        if (buf_size == -1)
-            buf_size = 1024;
-
-        buf = malloc(buf_size);
-
-        /* This test isn't essential, skip it in case of error */
-        if (buf) {
-            if (getpwnam_r(SECURITY_SERVER_MIDDLEWARE_USER, &pw, buf, buf_size, &ppw) == 0 && ppw)
-                middleware_uid = pw.pw_uid;
-
-            free(buf);
-        }
-    }
-
-    /* Middleware services need to run as root or middleware/app user */
-    if (cr.uid != 0 && cr.uid != middleware_uid)
-    {
-        retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
-        SEC_SVR_ERR("Non root process has called API: %d", cr.uid);
-        goto error;
-    }
-
-    /* Read command line of the PID from proc fs */
-    exe = read_exe_path_from_proc(cr.pid);
-    if (exe == NULL)
-    {
-        /* It's weired. no file in proc file system, */
-        retval = SECURITY_SERVER_ERROR_FILE_OPERATION;
-        SEC_SVR_ERR("Error on opening /proc/%d/exe", cr.pid);
-        goto error;
-    }
-
-    *pid = cr.pid;
-
-error:
-    if (exe != NULL)
-        free(exe);
-
-    return retval;
-#endif
-}
-
-/* Get app PID from socked and read its privilege (GID) list
- * from /proc/<PID>/status.
- *
- * param 1: socket descriptor
- * param 2: pointer for hold returned array
- *
- * ret: size of array or -1 in case of error
- *
- * Notice that user must free space allocated in this function and
- * returned by second parameter (int * privileges)
- * */
-int get_client_gid_list(int sockfd, int **privileges)
-{
-    int ret;
-    //for read socket options
-    struct ucred socopt;
-    unsigned int socoptSize = sizeof(socopt);
-    //buffer for store /proc/<PID>/status filepath
-    const int PATHSIZE = 24;
-    char path[PATHSIZE];
-    //file pointer
-    FILE *fp = NULL;
-    //buffer for filelines
-    const int LINESIZE = 256;
-    char fileLine[LINESIZE];
-    //for parsing file
-    char delim[] = ": ";
-    char *token = NULL;
-
-
-    //clear pointer
-    *privileges = NULL;
-
-    //read socket options
-    ret = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &socopt, &socoptSize);
-    if (ret != 0)
-    {
-        SEC_SVR_ERR("%s", "Error on getsockopt");
-        return -1;
-    }
-
-    //now we have PID in sockopt.pid
-    bzero(path, PATHSIZE);
-    snprintf(path, PATHSIZE, "/proc/%d/status", socopt.pid);
-
-    fp = fopen(path, "r");
-    if (fp == NULL)
-    {
-        SEC_SVR_ERR("%s", "Error on fopen");
-        return -1;
-    }
-
-    bzero(fileLine, LINESIZE);
-
-    //search for line beginning with "Groups:"
-    while (strncmp(fileLine, "Groups:", 7) != 0)
-    {
-        if (NULL == fgets(fileLine, LINESIZE, fp))
-        {
-            SEC_SVR_ERR("%s", "Error on fgets");
-            fclose(fp);
-            return -1;
-        }
-    }
-
-    fclose(fp);
-
-    //now we have "Groups:" line in fileLine[]
-    ret = 0;
-    strtok(fileLine, delim);
-    while ((token = strtok(NULL, delim)))
-    {
-        //add found GID
-        if (*privileges == NULL)
-        {
-            //first GID on list
-            *privileges = (int*)malloc(sizeof(int) * 1);
-            if (*privileges == NULL)
-            {
-                SEC_SVR_ERR("%s", "Error on malloc");
-                return -1;
-            }
-            (*privileges)[0] = atoi(token);
-        }
-        else
-        {
-            *privileges = realloc(*privileges, sizeof(int) * (ret + 1));
-            (*privileges)[ret] = atoi(token);
-        }
-
-        ret++;
-    }
-
-    //check if we found any GIDs for process
-    if (*privileges == NULL)
-    {
-        SEC_SVR_DBG("%s %d", "No GIDs found for PID:", socopt.pid);
-    }
-    else
-    {
-        SEC_SVR_DBG("%s %d", "Number of GIDs found:", ret);
-    }
-
-    return ret;
-}
-
diff --git a/src/include/SLP_security-model_PG.h b/src/include/SLP_security-model_PG.h
deleted file mode 100644 (file)
index 0151c15..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * @defgroup SLP_PG_SECURITY Security and Permissions
- * @ingroup SLP_PG
- * @{
- *      @brief  <em class="ref">Also see </em>  [ @ref SecurityFW ]
- *      @defgroup CertificateManager_PG
- *      @defgroup Security_Server_PG
- *      @defgroup SecureStorage_PG
- *      @}
- *      @defgroup SLP_PG_SECURITY
- *      @ingroup SLP_PG
- *      @{
-
-<h1 class="pg">Security Requirements</h1>
-<h2>Privileges </h2>
-<p>All processes MUST have least privilege to operate their own purpose. middleware daemons might run as root to satisfy their functional requirements, but there MUST BE NO application process which is running as root. In this document application represents all processes which has user interface to the end user.</p>
-<p>Each application process should have different privileges to satisfy least privilege, therefore there should be an entity to take care of process privileges.</p>
-<p>If an application process requires higher (system or root) privilege to provide some function, the function must be implemented in a middleware daemon and the function must be provided as an API to application</p>
-<h2>Application Sandboxing</h2>
-<p>All applications MUST NOT interfere each other. Interference covers killing other processes, modify or delete other application's files, overwrite or read other application process' memory area, masquerading other applications, and reading other application's sensitive files.</p>
-<h2>Middleware Resource Protection</h2>
-<p>All middleware resources MUST be protected by unauthorized access from applications. If the middleware is a daemon process, the process must not be interfered by applications, if the middleware is a library and the resources of the middleware are files, then the files must not be modified by unauthorized process.</p>
-<p>The resources must be protected at the resource level, not API level because API could be easily detoured</p>
-<h2>Privilege Escalation</h2>
-<p>There should be no privilege escalation, but by some management and/or manufacturing reason, unpredicted privilege escalation might be necessary. In this situation the modules which require privilege escalation MUST be highly reviewed and managed by developers and security manager.</p>
-<h1 class="pg">Security Model</h1>
-<h2>Background Information</h2>
-<h3>Discretionary Access Control</h3>
-<p>Linux kernel have supported discretionary access control (DAC) from the very beginning which controls access based on user ID, group ID of a process and owner of file that the process tries to access. This access control mechanism has been evolved with the Linux system evolution, additionally, SLP is not an embedded Linux platform but a normal Linux platform, therefore SLP has full support on DAC.</p>
-<p>In Linux all process is executed with user ID and groups, normally inherited by parent process. The processes which are executed in booting script will be executed as root user because the parent process "init" is root process. Any other user processes including user shell will be executed as an user that is logged in by the console login process. The groups that the process belongs to are also inherited by parent process, the list of group ID is assigned when the user is logged in based on "/etc/group" file. A process can be belonged more than thousand of groups (max 65,536 but I think too many groups might occur some problem).</p>
-<p>Only root process can change user ID and groups of the process by calling setuid() and setgroups() function, so if a root process is changed user to non root, then it can never change its user ID and groups again.</p>
-<p>There is a special feature to change user ID even the process is not owned by root user. If the executable file has setuid sticky bit, then the process will be executed as the owner of executable files. This is very important for access control because it can produce "privilege escalation" which can harm the platform security. In Linux PC, utilities such as "sudo" and "su" has this feature because these command need to change user to root or other user ID. These utilities first executed as root user and then changes to other user ID if needed.</p>
-<p>In Linux file system, all files are labeled with security context which describes owner user ID and group ID of the file and the permission of each accessible entity which are owner, group, and others. Permissions are consisting of read, write, and execute for each entity. If accessing process's user ID is same to owner of the file to be accessed, then the owner's permission is applied, if the process has the group that is labeled on the file, then the group's permission is applied, if not, then the other's permission is applied. All these functions are implemented in Linux kernel, so you don't need anything more for the feature. By the way, root process bypasses all the permission checking, that is root process can access all files. You can refer to Linux fundamental documents for this feature.</p>
-<p>The owner of a file can change permission of the file but, cannot change owner of the file. Only root process can change owner of the file, so if you want to change owner of a file, you have to be root.</p>
-<h3>Mandatory Access Control</h3>
-<p>DAC is great security feature of Linux, but sometime DAC is not sufficient to protect platform. DAC is based on user ID, group and file’s permissions, the granularity is limited to user ID level, in some way platform may need more precise access control than DAC. Mandatory Access Control (MAC) provides this security feature to give better and precise access control based on labeling and policy.</p>
-<p>MAC was not a part of standard Linux in the beginning, but since there were several requirements, so from kernel 2.6 version, some of the MAC mechanisms have been added to main line kernel source as optional features.</p>
-<p>MAC needs security context labeling and policy to control. Usually, all files have its security context described in extended attribute(xattr) of file system or some other places if xattr is not supported. Policy describes which subject (process) has permission to do something (operation) to some object. It doesn’t refer to owner and permission of the DAC field, just refer to security context of subject and object, and then searches allowed operations. Object can be files, directories, system calls, sockets and so on, each MAC mechanism has different set of objects.</p>
-<p>Using MAC, even root process can be denied to access some important object and some chosen root process can be allowed. Currently there are many MAC mechanisms such as SELinux, App-Armor, SMACK, RBAC, grsecurity and so on, and each of them has different objectives and approach.</p>
-<h2>Security Model</h2>
-<p>Since SLP is a Linux platform, its security model is similar to other Linux platform’s security model. In SLP, DAC and MAC are used, but biggest difference is that we need user space access control such as telephony, system management and so on.</p>
-<h3>Discretionary Access Control</h3>
-<p>- <b><i>User ID policy for processes</i></b></p>
-<p>All middleware daemons are running as root user ID, it's natural because daemons are executed by init process which is root process. There are a few exceptions that are not running as root even though the process is executed by init process. They are menu-screen, voice-call-daemon, and indicator. The reason is that the exceptional processes are executed by init process but they are not middleware, but applications. These special processes maybe increased at any time.</p>
-<p>Normal applications are executed as non root user ID. To achieve application sandboxing, all applications should run as all different user IDs, but it might occur complexity to the platform, so all the inhouse applications are executed as same user, and each 3rd party application will be executed as each different user ID.</p>
-<p><b><i>- Group ID for fine grained access control</i></b></p>
-<p>In Linux, a single process can be owned by a single user ID, but it can be belonged to multiple group IDs (max 65,536). In current desktop Linux such as Ubuntu, they use group ID to enforce access control for shared objects, such as CD-ROM, printer, audio, and so on. In SLP, we will use group ID as same usage, but the object will be different than normal desktop Linux, such as telephony, contact, and so on.</p>
-<p>As a result, each application will be given different group IDs based on its required privilege.</p>
-<p><i><b>- Security context on files</b></i></p>
-<p>For security and safety reason, basically all files in SLP owned by root as other Linux platform does, and then, non root user process cannot modify any files. The permission of normal files will be "rw-r--r--" which means only owner can modify or delete and the group member and others only can read, this is also same as other Linux platform. Lastly permission of executive files will be "rwxr-xr-x", so anybody can execute them, and also same as others.</p>
-<p>But there are many special files to be shared and modified by non root processes for example database files and device files in dev file system. In these cases, group ID of file is used. A shared file is owned by root but belonged to proper group ID which describes the file's content or object. The permission of the file could be "rw-rw-r--" to allow the processes belonged to the group can modify the file.</p>
-<p>There are some secret files to be protected by unauthorized read operation, then we can use same method as above but only difference will be no read permission to others, such as "rw-------", or "rw-rw----".</p>
-<p>Finally, there will be newly created files from middleware daemons and applications. There is default umask "022" , so if the created file is from middleware daemon, then the context of the file will be "root:root rw-r--r--", which means only root can modify and other users can read the file, if an application creates a file, then context wiil be "app_user:app_user rw-r--r--", so only the application can modify the file. This is normal usage but there must be some special cases which the file should be shared within applications. But, chown command and function only works under root privilege so applications cannot change owner of created files, so only thing possible is to change permission by chmod function. But there is only one option, share to none or share to all.</p>
-<h3>Mandatory Access Control</h3>
-<p>Mandatory access control(MAC) is currently out of scope of the SLP because there is almost no concrete threat which could be protected by MAC. Only one possible threat is that the network access by unauthorized process when there is a connected interface is already created. The adversary can monitor network interface status and if there is a new interface created, then it can use socket directly and it's possible to send some data by the socket. It's not possible to protect only by DAC.</p>
-<h2>User Space</h2>
-<p>There are many objects in user space such as making a phone call, sending a SMS message, which are not recognizable by kernel because thses objects are implemented in a daemon process, applications will request access by IPC and the kernel cannot manage inside of IPC messages. In these cases we must have a user space trusted entity which judges and controls access to such objects, which sits between applications and middleware daemons.</p>
-<p>To enable this, the entity must get identity of the subject application and object to be accessed, but it's not easy because some of the IPC mechanisms don't support peer's identity acquisition. For example all the dbus messages are routed by dbus daemon, so the receiver only guarantees dbus daemon sent the message, not the original sender of the message. Therefore, we have to support such mechanism to guarantee the original sender's identity to the final receiver along with reliable and secure access decision mechanism.</p>
-<p>To enforce access control, there must be an access policy which should be stored securely and it must be reliable. In SLP we utilized group ID for this policy. All processes have their user ID and groups which are controlled by kernel, each user space object is described as a group ID and the subject process will have the group ID if the application process has corresponding group ID then the access to be allowed, if not, the access will be denied.</p>
-<p>One more function required is that the enforcing entity needs to know other processes groups information. proc file system can be used. In proc file system, there is a file named "status", which describes various information about a process including all groups that the process belong to.</p>
-<h1 class="pg">Implementation</h1>
-<h2>User ID and Group ID Administration for Processes</h2>
-<p>As described above, all the daemons will be run by root, this is natural because all the booting scripts are executed by init process which is a root process, so all the processes executed by booting scripts will be run as root automatically. But there are some exceptions. There are some processes which are executed by booting scripts but not actually daemons such as menu screen and indicator. These processes must drop their privilege to a normal user, so in the beginning of their code, they change their user ID and groups to a normal user.</p>
-<p>All other applications will be executed by AUL (application utility library). When a new application process is requested to be executed, AUL daemon (launchpad) which is a root process receives the request, fork() and execute requested application in the child process. During this process, after forking a process, the launchpad child process changes its user ID to a corresponding user ID, changes matching groups, changes home directory, and execute the application. This is similar to su command in Linux environment.</p>
-<p>When a new application is installed, package manager adds a new user which has same user name with package name but substituting dot '.' to underscore '_'. But this feature is currently out of scope of the SLP.</p>
-<p>The group ID will be described as manifest permission item which described in control file of the debian package. Manifest permission items and group IDs will not correspond 1 to 1, basically one permission item will mean a set of group IDs to enable the permission, the sets might consist of 1 group ID or many group IDs. When a new application is installed, these groups will be assigned to the user ID, this could be implemented by adduser command. But this feature is currently out of scope of the SLP.</p>
-<h2>Changing Owner, Group and Permissions for Files</h2>
-<p>Since SLP uses debian package for the internal build system, all files which are installed by debian are automatically owned by root and their permissions set to 0644 (rw-r--r--), which means only root can modify and other processes only can read. But in the platform there are various files which should be modified by applications also, so we need to modify the ownership and permission intentionally.</p>
-<p>The only way to do this is by using postinst script of each of the debian package. On each package if there are some files should be shared, the package developer should add a few line to postinst file to change owner ship and permission to the files. To change owner, of a file, you have to be a root, if you are using fakeroot, the chown will not be affected.</p>
-*/
-/**
-*@}
-*/
diff --git a/src/include/SLP_security-server_PG.h b/src/include/SLP_security-server_PG.h
deleted file mode 100644 (file)
index acb8ac1..0000000
+++ /dev/null
@@ -1,350 +0,0 @@
-/**
- *
- * @ingroup   SLP_PG
- * @defgroup  Security_Server_PG Security Server
-@{
-
-<h1 class="pg">Introduction</h1>
-<p>In Linux system, access control is enforced in the kernel space objects such as file, socket, directory, and device which are all described as files. In SLP, many objects are defined in user space which cannot be described as file, for example, make a phone call, send a SMS message, connect to the Internet, and modify SIM password. Some of the objects in user space are very sensitive to the platform and the phone business as well as user's property. Therefore the user space objects needed to be protected.</p>
-<p>To protect such user space objects, there must be a kind of credential to decide access result, and the credential must be trusted. Since process has privileges and the objects only has label, so some trusted entity should check the process has right privilege to access objects, and the security hooks to check this privilege should be located in the each middleware service daemons which provide the objects to the applications.</p>
-<p>Security Server uses group IDs of Linux system that are assigned to each process. In detail, if a process requests to get some user-space service to a middleware daemon, the middleware daemon requests to check privilege of some process, then the security server checks given gid is assigned to the process or not. If yes, then return yes, if no, then return no.</p>
-<p>If an application and middleware daemon uses Linux standard IPC such as Unix domain socket, there is no need to introduce 3rd party process to check gid that the process has. But some of service uses non Linux standard IPC such as telephony - using dbus - which the peer's credential is not propagated to the other peer. As a result to meet all the system's environment, we introduce Security Server.</p>
-<p>
-Security Server uses a random token named "cookie" to identify a process, the cookie needed not to be abled to guess easily, so it's quite long (currently 20 bytes), and only kept by Security Server process memory</p>
-
-<h1 class="pg">Security Server Architecture</h1>
-@image html SLP_Security-Server_PG_image001.png
-<p>Above fiture explains software architecture of Security Server. It is client-server structure, and communicates by IPC. The IPC must be point-2-point mechanism such as UNIX domain socket, not server related IPC such as dbus, because it's not easy to guarantee the other peer's security.</p>
-<p>Application or middleware process can call Security Server API to assign a new cookie or checking privilege of the given cookie. In this case, client library authenticates IPC peer and check the peer is Security Server process. In the same sense, Security Server authenticates client also.</p>
-<p>Application requests cookie to Security Server before requesting the service to the middleware daemon. Security Server authenticates the client, generates a random cookie, stores the cookie into local memory, and responds to the client with the cookie value. Client loads the cookie in the request message and sends to the middleware server, then the receiver middleware daemon check the privilege of the given cookie by calling Security Server API. Security Server compares received cookie value with stored cookie, checks and responds to the middleware daemon. Finally middleware daemon knows the client's privilege and it decides continue or block the request.</p>
-
-<h2>Sub components</h2>
-
-<h3>Client library</h3>
-@image html SLP_Security-Server_PG_image002.png
-<p>Client library is linked to application or middleware daemon. Therefore it belongs to the caller process, so uid, pid, and groups are also same. If the application calls cookie request API, the client compose cookie request message and sends to the Security Server and wait for the response. After receiving the response, first checks the response is from Security Server, and if it's true, it stores cookie into cookie container.</p>
-<p>Middleware daemon also links same client library, but by the difference of the calling APIs, the functions are different. Middleware daemon first receives cookie value loaded in service request from the client, and then the middleware calls Security Server API to check the cookie has the privilege to the service and waits for the response. After receiving the response, it authenticates the response is really from Security Server, and continue service by the result of the API.</p>
-
-<h3>Security Server Daemon</h3>
-@image html SLP_Security-Server_PG_image003.png
-<p>Security Server daemon is a Unix domain socket server, but it only has single thread and single process to get rid of race condition for the proc file system and cookie list to be shared. It’s easy to manage, more secure and the Security Server itself doesn't need to maintain a session for a long time.</p>
-<p>When request API is received from the client, Security Server first parses, and authenticates the message, and creates cookie or checks privilege. Cookie is a 20 bytes random string too hard to be guessed. So it's hard to be spoofed.</p>
-<p>Cookie generator generates a cookie based on proc file system information of the client process with group IDs the client belongs to, and privilege checker searches received cookie value with stored cookie list and checks the privilege.</p>
-<p>Cookie list is a linked list implemented in memory and it stores and manages generated cookie.</p>
-
-<h1 class="pg">Dependency</h1>
-<p>The Security Server has high dependency on Linux kernel, precisely the proc file system. Since Security Server refers to proc file system with processes group ID, so the kernel must support group ID representation on the proc file system.</p>
-<p>In kernel version 2.6, there is a file in proc file system "/proc/[pid]/status" which describes various information about the process as text, it has a line named "Groups:" and it lists the group IDs that the process is belonged to. But there is a drawback in this file, it only shows at most 32 group IDs, if number of groups of the process is bigger than 32, it ignores them.</p>
-<p>To enable to show all the groups you have to patch the kernel source code to show more groups than 32, but there is another drawback. All files in the proc file system has size limit to 4k bytes because the file buffer size is 4k bytes, so it's not possible to show all possible groups of the process (64k), but currently number of all groups in the LiMo platform is much lower than the size, so it's not a big problem. But near future we need to apply this patch into kernel mainline source code by any form.</p>
-
-<h1 class="pg">Scenarios</h1>
-@image html SLP_Security-Server_PG_image004.png
-<p>Security Server process view is described in figure above. It's explained in above, so it's not necessary to explain again. But one possible question may arise, that why do we need Security Server, that the service daemon can authenticates application process by the IPC, and the daemon can check proc file system by itself, so it seems that we may not need to have Security Server at all<p>
-@image html SLP_Security-Server_PG_image005.png
-<p>But there is exceptional process view described in figure above. If the middleware's IPC mechanism is dbus, then the daemon cannot guarantee the identity of the requesting application. In this case, there is no possible way to check and authenticate application from the middleware daemon directly. We need a trusted 3rd party to guarantee such identity and privilege, therefore Security Server is required.</p>
-<p>As described above, the cookie value is the key of the security of Security Server. The cookie value must not to be exposed into the platform, the cookie value must be stored securely that only Security Server and the application process knows the value. Even the middleware daemon should not cache the cookie for the security reason</p>
-
-<h1 class="pg">APIs</h1>
-
-<h3 class="pg">security_server_get_gid</h3>
-<table>
-    <tr>
-        <td>
-            API Name:
-        </td>
-        <td>
-            gid_t security_server_get_gid(const char *object)
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Input Parameter:
-        </td>
-        <td>
-            object name as Null terminated string
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Output Parameter:
-        </td>
-        <td>
-            N/A
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Return value:
-        </td>
-        <td>
-            On success, returns the integer gid of requested object.<br>
-            On fail, returns negative integer
-        </td>
-    </tr>
-</table>
-This API returns the gid from given object name. This API is only allowed to be called from middleware service daemon which is running under root privilege
-
-<h3 class="pg">security_server_get_object_name</h3>
-<table>
-    <tr>
-        <td>
-            API Name:
-        </td>
-        <td>
-            int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size)
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Input Parameter:
-        </td>
-        <td>
-            gid, max_object_size
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Output Parameter:
-        </td>
-        <td>
-            object as null terminated string
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Return value:
-        </td>
-        <td>
-            On success, returns 0<br>
-            On fail, returns negative integer
-        </td>
-    </tr>
-</table>
-This API is opposite with security_server_get_gid(). It converts given gid to object name which buffer size is max_object_size. If object name is bigger then max_object_size then it returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
-
-<h3 class="pg">security_server_request_cookie</h3>
-<table>
-    <tr>
-        <td>
-            API Name:
-        </td>
-        <td>
-            gid_t security_server_request_cookie(char *cookie, size_t max_cookie)
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Input Parameter:
-        </td>
-        <td>
-            max_cookie
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Output Parameter:
-        </td>
-        <td>
-            cookie
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Return value:
-        </td>
-        <td>
-            On success, returns 0<br>
-            On fail, returns negative integer
-        </td>
-    </tr>
-</table>
-This API requests a cookie to Security Server. max_cookie is the size of buffer cookie to be filled with cookie value, if max_cookie smaller then cookie size, then this API returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
-
-<h3 class="pg">security_server_get_cookie_size</h3>
-<table>
-    <tr>
-        <td>
-            API Name:
-        </td>
-        <td>
-            int security_server_get_cookie_size(void)
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Input Parameter:
-        </td>
-        <td>
-            N/A
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Output Parameter:
-        </td>
-        <td>
-            N/A
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Return value:
-        </td>
-        <td>
-            size of cookie value
-        </td>
-    </tr>
-</table>
-This API simply returns the size of cookie.
-
-<h3 class="pg">security_server_check_privilege</h3>
-<table>
-    <tr>
-        <td>
-            API Name:
-        </td>
-        <td>
-            int security_server_check_privilege(const char *cookie, gid_t privilege)
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Input Parameter:
-        </td>
-        <td>
-            cookie, privilege
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Output Parameter:
-        </td>
-        <td>
-            N/A
-        </td>
-    </tr>
-    <tr>
-        <td>
-            Return value:
-        </td>
-        <td>
-            On success, returns 0<br>
-            On fail, returns negative integer
-        </td>
-    </tr>
-</table>
-This API checks the cookie value has privilege for given gid. This API should be called by middleware server only after application embed cookie into the request message and sent to the middleware server. The middleware server should aware with the privilege parameter because it knows the object which the client application tries to access.
-
-
-<h1 class="pg">Implementation Guide</h1>
-
-<h2>Middleware server side</h2>
-<p>
-In middleware, implementation is focused on checking privilege of the requested client application. To call security_server_check_privilege() API, you have to get the gid value first, and this can be achieved by calling security_server_get_gid() API. The pre-condition of this scenario is that the middleware server knows the name of the object. Once you get the gid values, you can cache them for better performance. </p>
-<p>
-Once a client application requests to access the middleware’s object, the client should embed cookie into the request message. If not, the security is not guaranteed. After getting request and embedded cookie, the middleware server call security_server_check_privilege() API to check the client is allowed to access the object, the security server will respond the result. Finally the server need to decide continue the service or not.</p>
-
-@code
-static gid_t g_gid;
-
-int get_gid()
-{
-    int ret;
-    // Get gid of telephony call - example object
-    ret = security_server_get_gid("telephony_call");
-    if(ret < 0)
-    {
-        return -1;
-    }
-    g_gid = ret;
-    return 0;
-}
-
-int main(int argc, char * argv[])
-{
-    char *cookie = NULL;
-    int ret, cookie_size;
-
-
-    ...
-
-
-        // Initially get gid about the object which is interested in
-        if(get_gid() < 0)
-            exit(-1);
-
-    // get cookie size and malloc it if you want
-    cookie_size = security_server_get_cookie_size();
-    cookie = malloc(cookie_size);
-
-    ...
-
-    // If a request has been received
-    // First parse the request and get the cookie value
-    // Let's assume that the buffer cookie is filled with received cookie value
-    ret = security_server_check_privilege(cookie, cookie_size);
-    if(ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-    {
-        // Access denied
-        // Send error message to client application
-    }
-    else if( ret != SECURITY_SERVER_SUCCESS)
-    {
-        // Error occurred
-        // Check error condition
-    }
-    else
-    {
-        // Access granted
-        // Continue service
-        ...
-    }
-
-
-    ...
-
-
-    free(cookie);
-    ...
-}
-@endcode
-
-<h2>Client application side</h2>
-<p>
-In client application, what you need is just request a cookie and embed it into request message</p>
-
-@code
-int some_platform_api()
-{
-    char *cookie = NULL;
-    int cookie_size, ret;
-
-    ...
-
-
-    // malloc the cookie
-    cookie_size = security_server_get_cookie_size();
-    cookie = malloc(cookie_size);
-
-    ...
-
-
-        // Request cookie from the security server
-        ret = security_server_request_cookie(cookie, cookie_size);
-    if(ret < 0)
-    {
-        // Some error occurred
-        return -1;
-    }
-
-    // embed cookie into the message and send to the server
-
-    ...
-    free(cookie);
-}
-@endcode
-
-*/
-/**
-*@}
-*/
diff --git a/src/include/security-server-comm.h b/src/include/security-server-comm.h
deleted file mode 100644 (file)
index ef558f4..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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 SECURITY_SERVER_COMM_H
-#define SECURITY_SERVER_COMM_H
-
-/* Message */
-typedef struct
-{
-    unsigned char version;
-    unsigned char msg_id;
-    unsigned short msg_len;
-} basic_header;
-
-typedef struct
-{
-    basic_header basic_hdr;
-    unsigned char return_code;
-} response_header;
-
-#define SECURITY_SERVER_MIDDLEWARE_USER "app"
-
-/* Message Types */
-// #define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST            0x05
-// #define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE           0x06
-#define SECURITY_SERVER_MSG_TYPE_GID_REQUEST                    0x07
-#define SECURITY_SERVER_MSG_TYPE_GID_RESPONSE                   0x08
-#define SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE               0xff
-
-/* Return code */
-#define SECURITY_SERVER_RETURN_CODE_SUCCESS                        0x00
-#define SECURITY_SERVER_RETURN_CODE_BAD_REQUEST                    0x01
-#define SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED          0x02
-#define SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED                 0x03
-#define SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED                  0x04
-#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT                 0x05
-#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE                 0x06
-#define SECURITY_SERVER_RETURN_CODE_SERVER_ERROR                   0x0e
-
-int return_code_to_error_code(int ret_code);
-int create_new_socket(int *sockfd);
-int safe_server_sock_close(int client_sockfd);
-int connect_to_server(int *fd);
-int accept_client(int server_sockfd);
-int authenticate_client_application(int sockfd, int *pid, int *uid);
-int authenticate_client_middleware(int sockfd, int *pid);
-int get_client_gid_list(int sockfd, int **privileges);
-int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code);
-int send_object_name(int sockfd, char *obj);
-int send_gid(int sockfd, int gid);
-int send_gid_request(int sock_fd, const char *object);
-int send_object_name_request(int sock_fd, int gid);
-int recv_get_gid_response(int sockfd, response_header *hdr, int *gid);
-int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size);
-
-int recv_hdr(int client_sockfd, basic_header *basic_hdr);
-
-int recv_generic_response(int sockfd, response_header *hdr);
-int check_socket_poll(int sockfd, int event, int timeout);
-int free_argv(char **argv, int argc);
-int get_socket_from_systemd(int *sockfd);
-
-#endif
diff --git a/src/include/security-server-common.h b/src/include/security-server-common.h
deleted file mode 100644 (file)
index 89f4216..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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 SECURITY_SERVER_COMMON_H
-#define SECURITY_SERVER_COMMON_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <sys/types.h>
-#include <dlog.h>
-
-/* Definitions *********************************************************/
-/* Return value. Continuing from return value of the client header file */
-#define SECURITY_SERVER_SUCCESS                              0
-#define SECURITY_SERVER_ERROR_SOCKET                         -1
-#define SECURITY_SERVER_ERROR_BAD_REQUEST                    -2
-#define SECURITY_SERVER_ERROR_BAD_RESPONSE                   -3
-#define SECURITY_SERVER_ERROR_SEND_FAILED                    -4
-#define SECURITY_SERVER_ERROR_RECV_FAILED                    -5
-#define SECURITY_SERVER_ERROR_NO_SUCH_OBJECT                 -6
-#define SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED          -7
-#define SECURITY_SERVER_ERROR_INPUT_PARAM                    -8
-#define SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL               -9
-#define SECURITY_SERVER_ERROR_OUT_OF_MEMORY                  -10
-#define SECURITY_SERVER_ERROR_ACCESS_DENIED                  -11
-#define SECURITY_SERVER_ERROR_SERVER_ERROR                   -12
-#define SECURITY_SERVER_ERROR_NO_SUCH_COOKIE                 -13
-#define SECURITY_SERVER_ERROR_NO_PASSWORD                    -14
-#define SECURITY_SERVER_ERROR_SOCKET_BIND                    -21
-#define SECURITY_SERVER_ERROR_FILE_OPERATION                 -22
-#define SECURITY_SERVER_ERROR_TIMEOUT                        -23
-#define SECURITY_SERVER_ERROR_POLL                           -24
-#define SECURITY_SERVER_ERROR_UNKNOWN                        -255
-
-/* Miscellaneous Definitions */
-#define SECURITY_SERVER_SOCK_PATH                          "/tmp/.security_server.sock"
-#define SECURITY_SERVER_DEFAULT_COOKIE_PATH                "/tmp/.security_server.coo"
-#define SECURITY_SERVER_DAEMON_PATH                        "/usr/bin/security-server"
-#define SECURITY_SERVER_COOKIE_LEN                         20
-#define MAX_OBJECT_LABEL_LEN                               32
-#define MAX_MODE_STR_LEN                                   16
-#define SECURITY_SERVER_MAX_OBJ_NAME                       30
-#define SECURITY_SERVER_MSG_VERSION                        0x01
-#define SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND          10000
-#define SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND          3000
-#define SECURITY_SERVER_DEVELOPER_UID                      5100
-#define SECURITY_SERVER_NUM_THREADS                        10
-#define MESSAGE_MAX_LEN                                    1048576
-
-/* API prefix */
-#ifndef SECURITY_SERVER_API
-#define SECURITY_SERVER_API __attribute__((visibility("default")))
-#endif
-
-
-
-/* Data types *****************************************************************/
-
-
-/* Cookie List data type */
-typedef struct _cookie_list
-{
-    unsigned char cookie[SECURITY_SERVER_COOKIE_LEN];   /* 20 bytes random Cookie */
-    int permission_len;                 /* Client process permissions (aka group IDs) */
-    pid_t pid;                          /* Client process's PID */
-    char *path;                         /* Client process's executable path */
-    int *permissions;                   /* Array of GID that the client process has */
-    char *smack_label;                                      /* SMACK label of the client process */
-    char is_roots_process;              /* Is cookie belongs to roots process */
-    struct _cookie_list *prev;              /* Next cookie list */
-    struct _cookie_list *next;              /* Previous cookie list */
-} cookie_list;
-
-
-/* Function prototypes ******************************************************/
-/* IPC */
-
-void printhex(const unsigned char *data, int size);
-
-/* Debug */
-#ifdef SECURITY_SERVER_DEBUG_TO_CONSOLE /* debug msg will be printed in console */
-#define SEC_SVR_DBG(FMT, ARG ...) fprintf(stderr, "[DBG:%s:%d] " FMT "\n", \
-                __FILE__, __LINE__, ##ARG)
-#define SEC_SVR_WRN(FMT, ARG ...) fprintf(stderr, "[WRN:%s:%d] " FMT "\n", \
-                __FILE__, __LINE__, ##ARG)
-#define SEC_SVR_ERR(FMT, ARG ...) fprintf(stderr, "[ERR:%s:%d] " FMT "\n", \
-                __FILE__, __LINE__, ##ARG)
-
-#else
-#ifdef LOG_TAG
-    #undef LOG_TAG
-#endif
-#define LOG_TAG "SECURITY_SERVER"
-#define SEC_SVR_ERR SLOGE
-#ifdef BUILD_TYPE_DEBUG        /* debug msg will be printed by dlog daemon */
-#define SEC_SVR_DBG SLOGD
-#define SEC_SVR_WRN SLOGW
-#else /* No debug output */
-
-#define SEC_SVR_DBG(FMT, ARG ...) do { } while(0)
-#define SEC_SVR_WRN(FMT, ARG ...) do { } while(0)
-#ifdef SECURE_SLOGD
-    #undef SECURE_SLOGD
-#endif
-#define SECURE_SLOGD(FMT, ARG ...) do { } while(0)
-#ifdef SECURE_SLOGW
-   #undef SECURE_SLOGW
-#endif
-#define SECURE_SLOGW(FMT, ARG ...) do { } while(0)
-
-#endif // BUILD_TYPE_DEBUG
-#endif // SECURITY_SERVER_DEBUG_TO_CONSOLE
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/src/include/security-server-util.h b/src/include/security-server-util.h
deleted file mode 100644 (file)
index c2f3ce3..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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 SECURITY_SERVER_UTIL_H
-#define SECURITY_SERVER_UTIL_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "security-server-common.h"
-int util_smack_label_is_valid(const char *smack_label);
-char *read_exe_path_from_proc(pid_t pid);
-int authorize_SS_API_caller_socket(int sockfd, char *required_API_label, char *required_rule);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /*SECURITY_SERVER_UTIL_H*/
diff --git a/src/include/smack-check.h b/src/include/smack-check.h
deleted file mode 100644 (file)
index 88360ba..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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 _SMACK_CHECK_H_
-#define _SMACK_CHECK_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * A very simple runtime check for SMACK on the platform
- * Returns 1 if SMACK is present, 0 otherwise
- */
-
-int smack_runtime_check(void);
-
-/*
- * A very simple runtime check for SMACK on the platform
- * Returns 1 if SMACK is present, 0 otherwise. If SMACK_ENABLED is not defined
- * It returns 0.
- */
-int smack_check(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _SMACK_CHECK_H_
diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0fad220
--- /dev/null
@@ -0,0 +1,53 @@
+PKG_CHECK_MODULES(COMMON_DEP
+    dlog
+    REQUIRED
+    )
+
+SET(COMMON_PATH ${PROJECT_SOURCE_DIR}/src/server)
+
+SET(COMMON_SOURCES
+    ${COMMON_PATH}/common/protocols.cpp
+    ${COMMON_PATH}/common/message-buffer.cpp
+    ${COMMON_PATH}/common/smack-check.cpp
+    ${COMMON_PATH}/dpl/log/src/abstract_log_provider.cpp
+    ${COMMON_PATH}/dpl/log/src/dlog_log_provider.cpp
+    ${COMMON_PATH}/dpl/log/src/log.cpp
+    ${COMMON_PATH}/dpl/log/src/old_style_log_provider.cpp
+    ${COMMON_PATH}/dpl/log/src/audit-smack-log.cpp
+    ${COMMON_PATH}/dpl/core/src/assert.cpp
+    ${COMMON_PATH}/dpl/core/src/binary_queue.cpp
+    ${COMMON_PATH}/dpl/core/src/colors.cpp
+    ${COMMON_PATH}/dpl/core/src/exception.cpp
+    ${COMMON_PATH}/dpl/core/src/noncopyable.cpp
+    ${COMMON_PATH}/dpl/core/src/serialization.cpp
+    ${COMMON_PATH}/dpl/core/src/singleton.cpp
+    )
+
+INCLUDE_DIRECTORIES(SYSTEM
+    ${COMMON_DEP_INCLUDE_DIRS}
+    )
+
+INCLUDE_DIRECTORIES(
+    ${COMMON_PATH}/common
+    ${COMMON_PATH}/dpl/core/include
+    ${COMMON_PATH}/dpl/log/include
+    )
+
+ADD_LIBRARY(${TARGET_SERVER_COMMON} SHARED ${COMMON_SOURCES})
+
+SET_TARGET_PROPERTIES(
+    ${TARGET_SERVER_COMMON}
+    PROPERTIES
+        COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=default"
+        SOVERSION 1.0.0
+        VERSION 1.0.0
+    )
+
+TARGET_LINK_LIBRARIES(${TARGET_SERVER_COMMON}
+    ${COMMON_DEP_LIBRARIES}
+    )
+
+################################################################################
+
+INSTALL(TARGETS ${TARGET_SERVER_COMMON} DESTINATION lib)
+
diff --git a/src/server/client/client-app-permissions.cpp b/src/server/client/client-app-permissions.cpp
new file mode 100644 (file)
index 0000000..927a2de
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-app-permissions.cpp
+ * @author      Pawel Polawski (pawel.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This file contain implementation of security_server_app_enable_permissions
+ *              and security_server_app_disable functions
+ */
+
+
+#include <stdio.h>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+
+#include <privilege-control.h>
+#include <security-server.h>
+
+
+SECURITY_SERVER_API
+int security_server_app_enable_permissions(const char *app_id, app_type_t app_type, const char **perm_list, int persistent)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    std::vector<std::string> permissions_list;
+
+    LogDebug("security_server_app_enable_permissions() called");
+
+    return try_catch([&] {
+        if ((NULL == app_id) || (strlen(app_id) == 0)) {
+            LogDebug("App_id is NULL");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+        if ((NULL == perm_list) || (strlen(perm_list[0]) == 0)) {
+            LogDebug("Perm_list is NULL");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        LogDebug("app_type: " << (int)app_type);
+        LogDebug("persistent: " << persistent);
+        LogDebug("app_id: " << app_id);
+
+        //put all strings in STL vector
+        for (int i = 0; perm_list[i] != NULL; i++) {
+            LogDebug("perm_list[" << i << "]: " << perm_list[i]);
+            permissions_list.push_back(std::string(perm_list[i]));
+        }
+
+        //put data into buffer
+        Serialization::Serialize(send, (int)AppPermissionsAction::ENABLE);   //works as a MSG_ID
+        Serialization::Serialize(send, persistent);
+        Serialization::Serialize(send, (int)app_type);
+        Serialization::Serialize(send, std::string(app_id));
+        Serialization::Serialize(send, permissions_list);
+
+        //send buffer to server
+        int result = sendToServer(SERVICE_SOCKET_APP_PERMISSIONS, send.Pop(), recv);
+        if (result != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << result);
+            return result;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, result);
+        return result;
+    });
+}
+
+
+SECURITY_SERVER_API
+int security_server_app_disable_permissions(const char *app_id, app_type_t app_type, const char **perm_list)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    std::vector<std::string> permissions_list;
+
+    LogDebug("security_server_app_disable_permissions() called");
+
+    return try_catch([&] {
+        if ((NULL == app_id) || (strlen(app_id) == 0)) {
+            LogDebug("App_id is NULL");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+        if ((NULL == perm_list) || (strlen(perm_list[0]) == 0)) {
+            LogDebug("Perm_list is NULL");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        LogDebug("app_type: " << (int)app_type);
+        LogDebug("app_id: " << app_id);
+
+        //put all strings in STL vector
+        for (int i = 0; perm_list[i] != NULL; i++) {
+            LogDebug("perm_list[" << i << "]: " << perm_list[i]);
+            permissions_list.push_back(std::string(perm_list[i]));
+        }
+
+        //put data into buffer
+        Serialization::Serialize(send, (int)AppPermissionsAction::DISABLE);   //works as a MSG_ID
+        Serialization::Serialize(send, (int)app_type);
+        Serialization::Serialize(send, std::string(app_id));
+        Serialization::Serialize(send, permissions_list);
+
+        //send buffer to server
+        int result = sendToServer(SERVICE_SOCKET_APP_PERMISSIONS, send.Pop(), recv);
+        if (result != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << result);
+            return result;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, result);
+        return result;
+    });
+}
+
+
+SECURITY_SERVER_API
+int security_server_app_has_privilege(const char *app_id,
+                                      app_type_t app_type,
+                                      const char *privilege_name,
+                                      int *result)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+
+    LogDebug("security_server_app_has_privilege() called");
+
+    try {
+        if ((NULL == app_id) || (strlen(app_id) == 0)) {
+            LogError("app_id is NULL or empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+        if ((NULL == privilege_name) || (strlen(privilege_name) == 0)) {
+            LogError("privilege_name is NULL or empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+        if (NULL == result) {
+            LogError("result is NULL");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        LogDebug("app_id: " << app_id);
+        LogDebug("app_type: " << static_cast<int>(app_type));
+        LogDebug("privilege_name: " << privilege_name);
+
+        //put data into buffer
+        Serialization::Serialize(send, static_cast<int>(PrivilegeCheckHdrs::CHECK_GIVEN_APP));
+        Serialization::Serialize(send, std::string(app_id));
+        Serialization::Serialize(send, static_cast<int>(app_type));
+        Serialization::Serialize(send, std::string(privilege_name));
+
+        //send buffer to server
+        int apiResult = sendToServer(SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME, send.Pop(), recv);
+        if (apiResult != SECURITY_SERVER_API_SUCCESS) {
+            LogError("Error in sendToServer. Error code: " << apiResult);
+            return apiResult;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, apiResult);
+        if (apiResult == SECURITY_SERVER_API_SUCCESS) {
+            Deserialization::Deserialize(recv, *result);
+        }
+        return apiResult;
+
+    } catch (MessageBuffer::Exception::Base &e) {
+        LogError("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
+    } catch (std::exception &e) {
+        LogError("STD exception " << e.what());
+    } catch (...) {
+        LogError("Unknown exception occured");
+    }
+
+    return SECURITY_SERVER_API_ERROR_UNKNOWN;
+}
+
+
+SECURITY_SERVER_API
+int security_server_app_caller_has_privilege(app_type_t app_type,
+                                             const char *privilege_name,
+                                             int *result)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+
+    LogDebug("security_server_app_caller_has_privilege() called");
+
+    try {
+        if ((NULL == privilege_name) || (strlen(privilege_name) == 0)) {
+            LogError("privilege_name is NULL or empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+        if (NULL == result) {
+            LogError("result is NULL");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        LogDebug("app_type: " << static_cast<int>(app_type));
+        LogDebug("privilege_name: " << privilege_name);
+
+        //put data into buffer
+        Serialization::Serialize(send, static_cast<int>(PrivilegeCheckHdrs::CHECK_CALLER_APP));
+        Serialization::Serialize(send, static_cast<int>(app_type));
+        Serialization::Serialize(send, std::string(privilege_name));
+
+        //send buffer to server
+        int apiResult = sendToServer(SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME, send.Pop(), recv);
+        if (apiResult != SECURITY_SERVER_API_SUCCESS) {
+            LogError("Error in sendToServer. Error code: " << apiResult);
+            return apiResult;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, apiResult);
+        if (apiResult == SECURITY_SERVER_API_SUCCESS) {
+            Deserialization::Deserialize(recv, *result);
+        }
+        return apiResult;
+
+    } catch (MessageBuffer::Exception::Base &e) {
+        LogError("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
+    } catch (std::exception &e) {
+        LogError("STD exception " << e.what());
+    } catch (...) {
+        LogError("Unknown exception occured");
+    }
+
+    return SECURITY_SERVER_API_ERROR_UNKNOWN;
+}
diff --git a/src/server/client/client-common.cpp b/src/server/client/client-common.cpp
new file mode 100644 (file)
index 0000000..2bd9091
--- /dev/null
@@ -0,0 +1,290 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-common.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This file is implementation of client-common functions.
+ */
+
+#include <fcntl.h>
+#include <poll.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+#include <dpl/singleton.h>
+#include <dpl/singleton_safe_impl.h>
+
+#include <message-buffer.h>
+
+#include <security-server.h>
+
+IMPLEMENT_SAFE_SINGLETON(SecurityServer::Log::LogSystem);
+
+namespace {
+
+const int POLL_TIMEOUT = 1000;
+
+void securityClientEnableLogSystem(void) {
+    SecurityServer::Singleton<SecurityServer::Log::LogSystem>::Instance().SetTag("SECURITY_SERVER_CLIENT");
+}
+
+int waitForSocket(int sock, int event, int timeout) {
+    int retval;
+    pollfd desc[1];
+    desc[0].fd = sock;
+    desc[0].events = event;
+
+    while((-1 == (retval = poll(desc, 1, timeout))) && (errno == EINTR)) {
+        timeout >>= 1;
+        errno = 0;
+    }
+
+    if (0 == retval) {
+        LogDebug("Poll timeout");
+    } else if (-1 == retval) {
+        int err = errno;
+        LogError("Error in poll: " << strerror(err));
+    }
+    return retval;
+}
+
+class SockRAII {
+public:
+    SockRAII()
+      : m_sock(-1)
+    {}
+
+    virtual ~SockRAII() {
+        if (m_sock > -1)
+            close(m_sock);
+    }
+
+    int Connect(char const * const interface) {
+        sockaddr_un clientAddr;
+        int flags;
+
+        if (m_sock != -1) // guard
+            close(m_sock);
+
+        m_sock = socket(AF_UNIX, SOCK_STREAM, 0);
+        if (m_sock < 0) {
+            int err = errno;
+            LogError("Error creating socket: " << strerror(err));
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+
+        if ((flags = fcntl(m_sock, F_GETFL, 0)) < 0 ||
+            fcntl(m_sock, F_SETFL, flags | O_NONBLOCK) < 0)
+        {
+            int err = errno;
+            LogError("Error in fcntl: " << strerror(err));
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+
+        memset(&clientAddr, 0, sizeof(clientAddr));
+
+        clientAddr.sun_family = AF_UNIX;
+
+        if (strlen(interface) >= sizeof(clientAddr.sun_path)) {
+            LogError("Error: interface name " << interface << "is too long. Max len is:" << sizeof(clientAddr.sun_path));
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+
+        strcpy(clientAddr.sun_path, interface);
+
+        LogDebug("ClientAddr.sun_path = " << interface);
+
+        int retval = TEMP_FAILURE_RETRY(connect(m_sock, (struct sockaddr*)&clientAddr, SUN_LEN(&clientAddr)));
+        if ((retval == -1) && (errno == EINPROGRESS)) {
+            if (0 >= waitForSocket(m_sock, POLLIN, POLL_TIMEOUT)) {
+                LogError("Error in waitForSocket.");
+                return SECURITY_SERVER_API_ERROR_SOCKET;
+            }
+            int error = 0;
+            size_t len = sizeof(error);
+            retval = getsockopt(m_sock, SOL_SOCKET, SO_ERROR, &error, &len);
+
+            if (-1 == retval) {
+                int err = errno;
+                LogError("Error in getsockopt: " << strerror(err));
+                return SECURITY_SERVER_API_ERROR_SOCKET;
+            }
+
+            if (error == EACCES) {
+                LogError("Access denied");
+                return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
+            }
+
+            if (error != 0) {
+                LogError("Error in connect: " << strerror(error));
+                return SECURITY_SERVER_API_ERROR_SOCKET;
+            }
+
+            return SECURITY_SERVER_API_SUCCESS;
+        }
+
+        if (-1 == retval) {
+            int err = errno;
+            LogError("Error connecting socket: " << strerror(err));
+            if (err == EACCES)
+                return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    int Get() {
+        return m_sock;
+    }
+
+private:
+    int m_sock;
+};
+
+} // namespace anonymous
+
+namespace SecurityServer {
+
+
+int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv) {
+    int ret;
+    SockRAII sock;
+    ssize_t done = 0;
+    char buffer[2048];
+
+    if (SECURITY_SERVER_API_SUCCESS != (ret = sock.Connect(interface))) {
+        LogError("Error in SockRAII");
+        return ret;
+    }
+
+    while ((send.size() - done) > 0) {
+        if (0 >= waitForSocket(sock.Get(), POLLOUT, POLL_TIMEOUT)) {
+            LogError("Error in poll(POLLOUT)");
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+        ssize_t temp = TEMP_FAILURE_RETRY(write(sock.Get(), &send[done], send.size() - done));
+        if (-1 == temp) {
+            int err = errno;
+            LogError("Error in write: " << strerror(err));
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+        done += temp;
+    }
+
+    do {
+        if (0 >= waitForSocket(sock.Get(), POLLIN, POLL_TIMEOUT)) {
+            LogError("Error in poll(POLLIN)");
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+        ssize_t temp = TEMP_FAILURE_RETRY(read(sock.Get(), buffer, 2048));
+        if (-1 == temp) {
+            int err = errno;
+            LogError("Error in read: " << strerror(err));
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+
+        if (0 == temp) {
+            LogError("Read return 0/Connection closed by server(?)");
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+
+        RawBuffer raw(buffer, buffer+temp);
+        recv.Push(raw);
+    } while(!recv.Ready());
+    return SECURITY_SERVER_API_SUCCESS;
+}
+
+int sendToServerAncData(char const * const interface, const RawBuffer &send, struct msghdr &hdr) {
+    int ret;
+    SockRAII sock;
+    ssize_t done = 0;
+
+    if (SECURITY_SERVER_API_SUCCESS != (ret = sock.Connect(interface))) {
+        LogError("Error in SockRAII");
+        return ret;
+    }
+
+    while ((send.size() - done) > 0) {
+        if (0 >= waitForSocket(sock.Get(), POLLOUT, POLL_TIMEOUT)) {
+            LogError("Error in poll(POLLOUT)");
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+        ssize_t temp = TEMP_FAILURE_RETRY(write(sock.Get(), &send[done], send.size() - done));
+        if (-1 == temp) {
+            int err = errno;
+            LogError("Error in write: " << strerror(err));
+            return SECURITY_SERVER_API_ERROR_SOCKET;
+        }
+        done += temp;
+    }
+
+    if (0 >= waitForSocket(sock.Get(), POLLIN, POLL_TIMEOUT)) {
+        LogError("Error in poll(POLLIN)");
+        return SECURITY_SERVER_API_ERROR_SOCKET;
+    }
+
+    ssize_t temp = TEMP_FAILURE_RETRY(recvmsg(sock.Get(), &hdr, MSG_CMSG_CLOEXEC));
+
+    if (temp < 0) {
+        int err = errno;
+        LogError("Error in recvmsg(): " << strerror(err) << " errno: " << err);
+        return SECURITY_SERVER_API_ERROR_SOCKET;
+    }
+
+    if (0 == temp) {
+        LogError("Read return 0/Connection closed by server(?)");
+        return SECURITY_SERVER_API_ERROR_SOCKET;
+    }
+
+    return SECURITY_SERVER_API_SUCCESS;
+}
+
+int try_catch(const std::function<int()>& func)
+{
+    try {
+        return func();
+    } catch (MessageBuffer::Exception::Base &e) {
+        LogError("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
+    } catch (std::exception &e) {
+        LogError("STD exception " << e.what());
+    } catch (...) {
+        LogError("Unknown exception occured");
+    }
+    return SECURITY_SERVER_API_ERROR_UNKNOWN;
+}
+
+} // namespace SecurityServer
+
+static void init_lib(void) __attribute__ ((constructor));
+static void init_lib(void)
+{
+    securityClientEnableLogSystem();
+}
+
+static void fini_lib(void) __attribute__ ((destructor));
+static void fini_lib(void)
+{
+
+}
+
diff --git a/src/server/client/client-common.h b/src/server/client/client-common.h
new file mode 100644 (file)
index 0000000..ff494b4
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-common.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This file constains implementation of common types
+ *              used in security server.
+ */
+
+#ifndef _SECURITY_SERVER_CLIENT_
+#define _SECURITY_SERVER_CLIENT_
+
+#include <vector>
+#include <functional>
+
+#include <message-buffer.h>
+
+#define SECURITY_SERVER_API __attribute__((visibility("default")))
+
+extern "C" {
+    struct msghdr;
+}
+
+namespace SecurityServer {
+
+typedef std::vector<unsigned char> RawBuffer;
+
+int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv);
+
+/*
+ * sendToServerAncData is special case when we want to receive file descriptor
+ * passed by Security Server on behalf of calling process. We can't get it with
+ * MessageBuffer.
+ *
+ * This function should be called _ONLY_ in this particular case.
+ *
+ */
+int sendToServerAncData(char const * const interface, const RawBuffer &send, struct msghdr &hdr);
+
+/*
+ * Decorator function that performs frequently repeated exception handling in
+ * SS client API functions. Accepts lambda expression as an argument.
+ */
+int try_catch(const std::function<int()>& func);
+
+} // namespace SecuritySever
+
+#endif // _SECURITY_SERVER_CLIENT_
diff --git a/src/server/client/client-cookie.cpp b/src/server/client/client-cookie.cpp
new file mode 100644 (file)
index 0000000..12fa21f
--- /dev/null
@@ -0,0 +1,324 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-cookie.cpp
+ * @author      Pawel Polawski (p.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This file contain implementation of cookie functions for getting cookies
+ */
+
+
+#include <cstdio>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+
+#include <security-server.h>
+
+SECURITY_SERVER_API
+int security_server_get_cookie_size(void)
+{
+    return SecurityServer::COOKIE_SIZE;
+}
+
+SECURITY_SERVER_API
+int security_server_request_cookie(char *cookie, size_t bufferSize)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    std::vector<char> receivedCookie;
+
+    LogDebug("security_server_request_cookie() called");
+
+    return try_catch([&] {
+        //checking parameters
+        if (bufferSize < COOKIE_SIZE) {
+            LogDebug("Buffer for cookie too small");
+            return SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL;
+        }
+        if (cookie == NULL) {
+            LogDebug("Cookie pointer empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        //put data into buffer
+        Serialization::Serialize(send, (int)CookieCall::GET_COOKIE);
+
+        //send buffer to server
+        int retval = sendToServer(SERVICE_SOCKET_COOKIE_GET, send.Pop(), recv);
+        if (retval != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << retval);
+            return retval;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, retval);
+        if (retval != SECURITY_SERVER_API_SUCCESS)
+            return retval;
+
+        Deserialization::Deserialize(recv, receivedCookie);
+        if (receivedCookie.size() != COOKIE_SIZE) {
+            LogDebug("No match in cookie size");
+            return SECURITY_SERVER_API_ERROR_BAD_RESPONSE;
+        }
+
+        memcpy(cookie, &receivedCookie[0], receivedCookie.size());
+        return retval;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_get_cookie_pid(const char *cookie)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    int pid;
+    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
+
+    LogDebug("security_server_get_cookie_pid() called");
+
+    if (cookie == NULL)
+        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+    //preprae cookie to send
+    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
+
+    return try_catch([&] {
+        //put data into buffer
+        Serialization::Serialize(send, (int)CookieCall::CHECK_PID);
+        Serialization::Serialize(send, key);
+
+        //send buffer to server
+        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
+        if (retval != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << retval);
+            return retval;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, retval);
+        if (retval != SECURITY_SERVER_API_SUCCESS)
+            return retval;
+
+        Deserialization::Deserialize(recv, pid);
+        return pid;
+    });
+}
+
+SECURITY_SERVER_API
+char * security_server_get_smacklabel_cookie(const char *cookie)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
+    std::string label;
+
+    LogDebug("security_server_get_smacklabel_cookie() called");
+
+    if (cookie == NULL)
+        return NULL;
+
+    //preprae cookie to send
+    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
+
+    try {
+        //put data into buffer
+        Serialization::Serialize(send, (int)CookieCall::CHECK_SMACKLABEL);
+        Serialization::Serialize(send, key);
+
+        //send buffer to server
+        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
+        if (retval != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << retval);
+            return NULL;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, retval);
+        if (retval != SECURITY_SERVER_API_SUCCESS)
+            return NULL;
+
+        Deserialization::Deserialize(recv, label);
+
+        return strdup(label.c_str());
+
+    } catch (MessageBuffer::Exception::Base &e) {
+        LogDebug("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
+    } catch (std::exception &e) {
+        LogDebug("STD exception " << e.what());
+    } catch (...) {
+        LogDebug("Unknown exception occured");
+    }
+
+    return NULL;
+}
+
+SECURITY_SERVER_API
+int security_server_check_privilege(const char *cookie, gid_t privilege)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
+
+    LogDebug("security_server_check_privilege() called");
+
+    if (cookie == NULL)
+        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+    //preprae cookie to send
+    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
+
+    return try_catch([&] {
+        //put data into buffer
+        Serialization::Serialize(send, (int)CookieCall::CHECK_PRIVILEGE_GID);
+        Serialization::Serialize(send, key);
+        Serialization::Serialize(send, (int)privilege);
+
+        //send buffer to server
+        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
+        if (retval != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << retval);
+            return retval;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, retval);
+        return retval;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_check_privilege_by_cookie(const char *cookie, const char *object, const char *access_rights)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
+
+    LogDebug("security_server_check_privilege_by_cookie() called");
+
+    if ((cookie == NULL) || (object == NULL) || (access_rights == NULL))
+        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+    //preprae cookie to send
+    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
+
+    std::string obj(object);
+    std::string access(access_rights);
+
+    return try_catch([&] {
+        //put data into buffer
+        Serialization::Serialize(send, (int)CookieCall::CHECK_PRIVILEGE);
+        Serialization::Serialize(send, key);
+        Serialization::Serialize(send, obj);
+        Serialization::Serialize(send, access);
+
+        //send buffer to server
+        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
+        if (retval != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << retval);
+            return retval;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, retval);
+        return retval;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_get_uid_by_cookie(const char *cookie, uid_t *uid)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
+
+    LogDebug("security_server_get_uid_by_cookie() called");
+
+    if ((cookie == NULL) || (uid == NULL))
+        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+    //preprae cookie to send
+    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
+
+    return try_catch([&] {
+        //put data into buffer
+        Serialization::Serialize(send, (int)CookieCall::CHECK_UID);
+        Serialization::Serialize(send, key);
+
+        //send buffer to server
+        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK_TMP, send.Pop(), recv);
+        if (retval != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << retval);
+            return retval;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, retval);
+        if (retval == SECURITY_SERVER_API_SUCCESS) {
+            int tmp;
+            Deserialization::Deserialize(recv, tmp);
+            *uid = static_cast<uid_t>(tmp);
+        }
+
+        return retval;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_get_gid_by_cookie(const char *cookie, gid_t *gid)
+{
+    using namespace SecurityServer;
+    MessageBuffer send, recv;
+    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
+
+    LogDebug("security_server_get_uid_by_cookie() called");
+
+    if ((cookie == NULL) || (gid == NULL))
+        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+    //preprae cookie to send
+    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
+
+    return try_catch([&] {
+        //put data into buffer
+        Serialization::Serialize(send, (int)CookieCall::CHECK_GID);
+        Serialization::Serialize(send, key);
+
+        //send buffer to server
+        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK_TMP, send.Pop(), recv);
+        if (retval != SECURITY_SERVER_API_SUCCESS) {
+            LogDebug("Error in sendToServer. Error code: " << retval);
+            return retval;
+        }
+
+        //receive response from server
+        Deserialization::Deserialize(recv, retval);
+        if (retval == SECURITY_SERVER_API_SUCCESS) {
+            int tmp;
+            Deserialization::Deserialize(recv, tmp);
+            *gid = static_cast<gid_t>(tmp);
+        }
+
+        return retval;
+    });
+}
+
diff --git a/src/server/client/client-get-gid.cpp b/src/server/client/client-get-gid.cpp
new file mode 100644 (file)
index 0000000..659e393
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-get-gid.cpp
+ * @author      Jan Olszak (j.olszak@samsung.com)
+ * @version     1.0
+ * @brief       This file constains implementation of get GID function.
+ */
+
+#include <stdio.h>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+
+#include <security-server.h>
+
+SECURITY_SERVER_API
+int security_server_get_gid(const char *objectName) {
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        if (NULL == objectName){
+            LogDebug("Objects name is NULL");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        int objectsNameLen = strlen(objectName);
+        if (0 == objectsNameLen || objectsNameLen > SECURITY_SERVER_MAX_OBJ_NAME){
+            LogDebug("Objects name is empty or too long");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+        Serialization::Serialize(send, std::string(objectName));
+
+        int retCode = sendToServer(
+          SERVICE_SOCKET_GET_GID,
+          send.Pop(),
+          recv);
+
+        if (retCode != SECURITY_SERVER_API_SUCCESS)
+            return retCode;
+
+        Deserialization::Deserialize(recv, retCode);
+
+        // Return if errors
+        if (retCode < 0)
+            return retCode;
+
+        // No errors, return gid
+        gid_t gid;
+        Deserialization::Deserialize(recv, gid);
+        return static_cast<int>(gid);
+    });
+}
+
diff --git a/src/server/client/client-get-object-name.cpp b/src/server/client/client-get-object-name.cpp
new file mode 100644 (file)
index 0000000..bef4124
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-get-object-name.cpp
+ * @author      Jan Olszak (j.olszak@samsung.com)
+ * @version     1.0
+ * @brief       This file constains implementation of get NAME function.
+ */
+
+#include <stdio.h>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+
+#include <security-server.h>
+
+SECURITY_SERVER_API
+int security_server_get_object_name(gid_t gid, char *pObjectName, size_t maxObjectSize)
+ {
+    using namespace SecurityServer;
+    return try_catch([&] {
+        if (pObjectName == NULL){
+            LogDebug("Objects name is NULL or empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+        Serialization::Serialize(send, gid);
+
+        int result = sendToServer(
+          SERVICE_SOCKET_GET_OBJECT_NAME,
+          send.Pop(),
+          recv);
+
+
+        if (result != SECURITY_SERVER_API_SUCCESS)
+            return result;
+
+        Deserialization::Deserialize(recv, result);
+
+        std::string retObjectName;
+        Deserialization::Deserialize(recv, retObjectName);
+
+        if(retObjectName.size() > maxObjectSize){
+            LogError("Objects name is too big. Need more space in pObjectName buffer.");
+            return SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL;
+        }
+
+        strcpy(pObjectName,retObjectName.c_str());
+
+        return result;
+
+    });
+}
+
diff --git a/src/server/client/client-open-for.cpp b/src/server/client/client-open-for.cpp
new file mode 100644 (file)
index 0000000..c8bf8ff
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-open-for-cookie.cpp
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of security-server API
+ *              for file opening.
+ */
+
+#include <cstring>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <security-server.h>
+
+SECURITY_SERVER_API
+int security_server_open_for(const char *filename, int *fd)
+{
+   using namespace SecurityServer;
+    try {
+        if (NULL == filename || std::string(filename).empty()) {
+            LogError("Error input param.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send;
+
+        Serialization::Serialize(send, std::string(filename));
+
+        struct msghdr hdr;
+        struct iovec iov;
+        struct cmsghdr *cmsg = NULL;
+        int retcode = -1;
+        int result = -1;
+        unsigned char cmsgbuf[CMSG_SPACE(sizeof(int))];
+
+        memset(&hdr, 0, sizeof(struct msghdr));
+        memset(cmsgbuf, 0, CMSG_SPACE(sizeof(int)));
+
+        iov.iov_base = &retcode;
+        iov.iov_len = sizeof(retcode);
+        hdr.msg_iov = &iov;
+        hdr.msg_iovlen = 1;
+
+        hdr.msg_control = cmsgbuf;
+        hdr.msg_controllen = CMSG_SPACE(sizeof(int));
+
+        result = sendToServerAncData(SERVICE_SOCKET_OPEN_FOR, send.Pop(), hdr);
+        if (result != SECURITY_SERVER_API_SUCCESS) {
+            *fd = -1;
+            return result;
+        }
+
+        if (hdr.msg_flags & MSG_CTRUNC) {
+            LogError("Not enough space for ancillary element array.");
+            *fd = -1;
+            return SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL;
+        }
+
+        for(cmsg = CMSG_FIRSTHDR(&hdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&hdr, cmsg)) {
+            if((SOL_SOCKET == cmsg->cmsg_level) && (SCM_RIGHTS == cmsg->cmsg_type)) {
+                memmove(fd, CMSG_DATA(cmsg), sizeof(int));
+            }
+        }
+
+        return retcode;
+    } catch (MessageBuffer::Exception::Base &e) {
+        LogDebug("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
+    } catch (std::exception &e) {
+        LogDebug("STD exception " << e.what());
+    } catch (...) {
+        LogDebug("Unknown exception occured");
+    }
+    return SECURITY_SERVER_API_ERROR_UNKNOWN;
+}
diff --git a/src/server/client/client-password.cpp b/src/server/client/client-password.cpp
new file mode 100644 (file)
index 0000000..48650c7
--- /dev/null
@@ -0,0 +1,277 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-password.cpp
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of password functions.
+ */
+
+#include <cstring>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+
+#include <security-server.h>
+
+namespace {
+
+inline bool isPasswordIncorrect(const char* pwd)
+{
+    return (pwd == NULL || strlen(pwd) == 0 || strlen(pwd) > SecurityServer::MAX_PASSWORD_LEN);
+}
+
+} // namespace anonymous
+
+SECURITY_SERVER_API
+int security_server_is_pwd_valid(unsigned int *current_attempts,
+                                 unsigned int *max_attempts,
+                                 unsigned int *valid_secs)
+{
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        if (NULL == current_attempts || NULL == max_attempts ||
+            NULL == valid_secs) {
+
+            LogError("Wrong input param");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+
+        *current_attempts = 0;
+        *max_attempts = 0;
+        *valid_secs = 0;
+
+        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_IS_PWD_VALID));
+
+        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
+        if (SECURITY_SERVER_API_SUCCESS != retCode) {
+            LogDebug("Error in sendToServer. Error code: " << retCode);
+            return retCode;
+        }
+
+        Deserialization::Deserialize(recv, retCode);
+
+        if(retCode == SECURITY_SERVER_API_ERROR_PASSWORD_EXIST) {
+            Deserialization::Deserialize(recv, *current_attempts);
+            Deserialization::Deserialize(recv, *max_attempts);
+            Deserialization::Deserialize(recv, *valid_secs);
+        }
+
+        return retCode;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_chk_pwd(const char *challenge,
+                            unsigned int *current_attempts,
+                            unsigned int *max_attempts,
+                            unsigned int *valid_secs)
+{
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        if (current_attempts == NULL || max_attempts == NULL || valid_secs == NULL ||
+            isPasswordIncorrect(challenge)) {
+            LogError("Wrong input param");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+
+        *current_attempts = 0;
+        *max_attempts = 0;
+        *valid_secs = 0;
+
+        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PWD));
+        Serialization::Serialize(send, std::string(challenge));
+
+        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
+        if (SECURITY_SERVER_API_SUCCESS != retCode) {
+            LogDebug("Error in sendToServer. Error code: " << retCode);
+            return retCode;
+        }
+
+        Deserialization::Deserialize(recv, retCode);
+
+        switch (retCode) {
+        case SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH:
+        case SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+        case SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED:
+        case SECURITY_SERVER_API_SUCCESS:
+            Deserialization::Deserialize(recv, *current_attempts);
+            Deserialization::Deserialize(recv, *max_attempts);
+            Deserialization::Deserialize(recv, *valid_secs);
+            break;
+        default:
+            break;
+        }
+
+        return retCode;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_set_pwd(const char *cur_pwd,
+                            const char *new_pwd,
+                            const unsigned int max_challenge,
+                            const unsigned int valid_period_in_days)
+{
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        if (NULL == cur_pwd)
+            cur_pwd = "";
+
+        if (isPasswordIncorrect(new_pwd) || strlen(cur_pwd) > MAX_PASSWORD_LEN) {
+            LogError("Wrong input param.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+
+        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD));
+        Serialization::Serialize(send, std::string(cur_pwd));
+        Serialization::Serialize(send, std::string(new_pwd));
+        Serialization::Serialize(send, max_challenge);
+        Serialization::Serialize(send, valid_period_in_days);
+
+        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
+        if (SECURITY_SERVER_API_SUCCESS != retCode) {
+            LogError("Error in sendToServer. Error code: " << retCode);
+            return retCode;
+        }
+
+        Deserialization::Deserialize(recv, retCode);
+
+        return retCode;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_set_pwd_validity(const unsigned int valid_period_in_days)
+{
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        MessageBuffer send, recv;
+
+        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_VALIDITY));
+        Serialization::Serialize(send, valid_period_in_days);
+
+        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
+        if (SECURITY_SERVER_API_SUCCESS != retCode) {
+            LogError("Error in sendToServer. Error code: " << retCode);
+            return retCode;
+        }
+
+        Deserialization::Deserialize(recv, retCode);
+
+        return retCode;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_set_pwd_max_challenge(const unsigned int max_challenge)
+{
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        MessageBuffer send, recv;
+
+        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_MAX_CHALLENGE));
+        Serialization::Serialize(send, max_challenge);
+
+        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
+        if (SECURITY_SERVER_API_SUCCESS != retCode) {
+            LogError("Error in sendToServer. Error code: " << retCode);
+            return retCode;
+        }
+
+        Deserialization::Deserialize(recv, retCode);
+
+        return retCode;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_reset_pwd(const char *new_pwd,
+                              const unsigned int max_challenge,
+                              const unsigned int valid_period_in_days)
+{
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        if (isPasswordIncorrect(new_pwd)) {
+            LogError("Wrong input param.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+
+        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_RST_PWD));
+        Serialization::Serialize(send, std::string(new_pwd));
+        Serialization::Serialize(send, max_challenge);
+        Serialization::Serialize(send, valid_period_in_days);
+
+        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
+        if (SECURITY_SERVER_API_SUCCESS != retCode) {
+            LogError("Error in sendToServer. Error code: " << retCode);
+            return retCode;
+        }
+
+        Deserialization::Deserialize(recv, retCode);
+
+        return retCode;
+    });
+}
+
+SECURITY_SERVER_API
+int security_server_set_pwd_history(int history_size)
+{
+    using namespace SecurityServer;
+
+    return try_catch([&] {
+        if (history_size > static_cast<int>(MAX_PASSWORD_HISTORY) || history_size < 0) {
+            LogError("Wrong input param.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+
+        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_HISTORY));
+        Serialization::Serialize(send, static_cast<unsigned int>(history_size));
+
+        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
+        if (SECURITY_SERVER_API_SUCCESS != retCode) {
+            LogError("Error in sendToServer. Error code: " << retCode);
+            return retCode;
+        }
+
+        Deserialization::Deserialize(recv, retCode);
+
+        return retCode;
+    });
+}
diff --git a/src/server/client/client-privilege-by-pid.cpp b/src/server/client/client-privilege-by-pid.cpp
new file mode 100644 (file)
index 0000000..1d96f18
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-check-privilege-by-pid.cpp
+ * @author      Jan Cybulski (j.cybulski@samsung.com)
+ * @version     1.0
+ * @brief       This file constains implementation of security-server API for
+ * checking privilege by process id.
+ */
+
+#include <stdio.h>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+#include <smack-check.h>
+#include <signal.h>
+
+#include <security-server.h>
+
+SECURITY_SERVER_API
+int security_server_check_privilege_by_pid(
+        int pid,
+        const char *object,
+        const char *access_rights) {
+    using namespace SecurityServer;
+    return try_catch([&] {
+        if (1 != smack_check())
+            return SECURITY_SERVER_API_SUCCESS;
+
+        // Checking whether a process with pid exists
+        if ((pid < 0) || ((kill(pid, 0) == -1) && (errno == ESRCH))) {
+            LogDebug("pid is invalid, process: " << pid << " does not exist");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        if (NULL == object || 0 == strlen(object)) {
+            LogDebug("object param is NULL or empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        if (NULL == access_rights || 0 == strlen(access_rights)) {
+            LogDebug("access_right param is NULL or empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+        Serialization::Serialize(send, pid);
+        Serialization::Serialize(send, std::string(object));
+        Serialization::Serialize(send, std::string(access_rights));
+
+        int result = sendToServer(
+          SERVICE_SOCKET_PRIVILEGE_BY_PID,
+          send.Pop(),
+          recv);
+
+        if (result != SECURITY_SERVER_API_SUCCESS)
+            return result;
+
+        Deserialization::Deserialize(recv, result);
+        return result;
+    });
+}
+
diff --git a/src/server/client/client-shared-memory.cpp b/src/server/client/client-shared-memory.cpp
new file mode 100644 (file)
index 0000000..f48dd69
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-shared-memory.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This file constains implementation of shared memory api.
+ */
+
+#include <stdio.h>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+#include <smack-check.h>
+
+#include <security-server.h>
+
+SECURITY_SERVER_API
+int security_server_app_give_access(const char *customer_label, int customer_pid) {
+    using namespace SecurityServer;
+    return try_catch([&] {
+        if (1 != smack_check())
+            return SECURITY_SERVER_API_SUCCESS;
+
+        if (NULL == customer_label || 0 == strlen(customer_label))
+        {
+            LogDebug("customer_label is NULL or empty");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        MessageBuffer send, recv;
+        Serialization::Serialize(send, std::string(customer_label));
+        Serialization::Serialize(send, customer_pid);
+
+        int result = sendToServer(
+          SERVICE_SOCKET_SHARED_MEMORY,
+          send.Pop(),
+          recv);
+
+        if (result != SECURITY_SERVER_API_SUCCESS)
+            return result;
+
+        Deserialization::Deserialize(recv, result);
+        return result;
+    });
+}
+
diff --git a/src/server/client/client-socket-privilege.cpp b/src/server/client/client-socket-privilege.cpp
new file mode 100644 (file)
index 0000000..5fcd286
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        client-socket-privilege.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This file constains implementation of socket privilege api.
+ */
+#include <memory>
+
+#include <sys/socket.h>
+#include <sys/smack.h>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+
+#include <message-buffer.h>
+#include <client-common.h>
+#include <protocols.h>
+#include <smack-check.h>
+
+#include <security-server.h>
+
+//static int get_exec_path(pid_t pid, std::string &exe)
+//{
+//    using namespace SecurityServer;
+//
+//    try{
+//        MessageBuffer send, recv;
+//        Serialization::Serialize(send, pid);
+//
+//        int result = sendToServer(
+//                SERVICE_SOCKET_EXEC_PATH,
+//                send.Pop(),
+//                recv);
+//        if(result != SECURITY_SERVER_API_SUCCESS)
+//            return result;
+//
+//        Deserialization::Deserialize(recv, result);
+//        if(result != SECURITY_SERVER_API_SUCCESS)
+//            return result;
+//
+//        Deserialization::Deserialize(recv, exe);
+//        return result;
+//    } catch (MessageBuffer::Exception::Base &e) {
+//        LogDebug("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
+//    } catch (std::exception &e) {
+//        LogDebug("STD exception " << e.what());
+//    } catch (...) {
+//        LogDebug("Unknown exception occured");
+//    }
+//    return SECURITY_SERVER_API_ERROR_UNKNOWN;
+//}
+
+SECURITY_SERVER_API
+int security_server_check_privilege_by_sockfd(int sockfd,
+                                              const char *object,
+                                              const char *access_rights)
+{
+    char *subject = NULL;
+    int ret;
+    std::string path;
+    std::unique_ptr<char, void (*)(void*)throw ()> subjectPtr(NULL, std::free);
+
+    //for get socket options
+    struct ucred cr;
+    size_t len = sizeof(struct ucred);
+
+    //SMACK runtime check
+    if (!SecurityServer::smack_runtime_check())
+    {
+        LogDebug("No SMACK support on device");
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    if (sockfd < 0 || !object || !access_rights)
+        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+    ret = smack_new_label_from_socket(sockfd, &subject);
+    if (ret >= 0) {
+        subjectPtr.reset(subject);
+        subject = NULL;
+    } else {
+        LogError("Failed to get new label from socket. Object="
+            << object << ", access=" << access_rights
+            << ", error=" << strerror(errno));
+        return SECURITY_SERVER_API_ERROR_SOCKET;
+    }
+
+    ret = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
+    if (ret < 0) {
+        LogError("Error in getsockopt(). Errno: "
+            << strerror(errno) <<  ", subject="
+            << (subjectPtr.get() ? subjectPtr.get() : "NULL")
+            << ", object=" << object << ", access=" << access_rights
+            << ", error=" << strerror(errno));
+        return SECURITY_SERVER_API_ERROR_SOCKET;
+    }
+
+    ret = security_server_check_privilege_by_pid(cr.pid, object, access_rights);
+
+    //Getting path for logs
+//    if (SECURITY_SERVER_API_SUCCESS != get_exec_path(cr.pid, path)) {
+//        LogError("Failed to read executable path for process " << cr.pid);
+//    }
+//
+//    if (ret == SECURITY_SERVER_API_SUCCESS)
+//        LogSecureDebug("SS_SMACK: caller_pid=" << cr.pid << ", subject=" <<
+//            (subjectPtr.get() ? subjectPtr.get() : "NULL") << ", object=" <<
+//            object << ", access=" << access_rights << ", result=" <<
+//            ret << ", caller_path=" << path.c_str());
+//    else
+//        LogSecureWarning("SS_SMACK: caller_pid=" << cr.pid << ", subject=" <<
+//            (subjectPtr.get() ? subjectPtr.get() : "NULL") << ", object=" <<
+//            object << ", access=" << access_rights << ", result=" <<
+//            ret << ", caller_path=" << path.c_str());
+
+    return ret;
+}
+
+SECURITY_SERVER_API
+char *security_server_get_smacklabel_sockfd(int fd)
+{
+    char *label = NULL;
+
+    if (!SecurityServer::smack_check())
+    {
+        LogDebug("No SMACK support on device");
+        label = (char*) malloc(1);
+        if (label) label[0] = '\0';
+        return label;
+    }
+
+    if (smack_new_label_from_socket(fd, &label) < 0)
+    {
+        LogError("Client ERROR: Unable to get socket SMACK label");
+        return NULL;
+    }
+
+    return label;
+}
diff --git a/src/server/common/connection-info.h b/src/server/common/connection-info.h
new file mode 100644 (file)
index 0000000..946b5c8
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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-info.h
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Definition of ConnectionInfo structure and ConnectionInfoMap type.
+ */
+
+#ifndef _CONNECTION_INFO_H_
+#define _CONNECTION_INFO_H_
+
+#include <map>
+#include <generic-socket-manager.h>
+#include <message-buffer.h>
+
+namespace SecurityServer
+{
+    struct ConnectionInfo {
+        InterfaceID interfaceID;
+        MessageBuffer buffer;
+    };
+
+    typedef std::map<int, ConnectionInfo> ConnectionInfoMap;
+} //namespace SecurityServer
+
+#endif //_CONNECTION_INFO_H_
diff --git a/src/server/common/message-buffer.cpp b/src/server/common/message-buffer.cpp
new file mode 100644 (file)
index 0000000..3fc090b
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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)
+ * @version     1.0
+ * @brief       Implementation of MessageBuffer.
+ */
+
+#include <message-buffer.h>
+
+#include <dpl/log/log.h>
+
+namespace SecurityServer {
+
+void MessageBuffer::Push(const RawBuffer &data) {
+    m_buffer.AppendCopy(&data[0], data.size());
+}
+
+RawBuffer MessageBuffer::Pop() {
+    size_t size = m_buffer.Size();
+    RawBuffer buffer;
+    buffer.resize(size + sizeof(size_t));
+    memcpy(&buffer[0], &size, sizeof(size_t));
+    m_buffer.FlattenConsume(&buffer[sizeof(size_t)], size);
+    return buffer;
+}
+
+bool MessageBuffer::Ready() {
+    CountBytesLeft();
+    if (m_bytesLeft == 0)
+        return false;
+    if (m_bytesLeft > m_buffer.Size())
+        return false;
+    return true;
+}
+
+void MessageBuffer::Read(size_t num, void *bytes) {
+    CountBytesLeft();
+    if (num > m_bytesLeft) {
+        LogDebug("Protocol broken. OutOfData. Asked for: " << num << " Ready: " << m_bytesLeft << " Buffer.size(): " << m_buffer.Size());
+        Throw(Exception::OutOfData);
+    }
+
+    m_buffer.FlattenConsume(bytes, num);
+    m_bytesLeft -= num;
+}
+
+void MessageBuffer::Write(size_t num, const void *bytes) {
+    m_buffer.AppendCopy(bytes, num);
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/common/message-buffer.h b/src/server/common/message-buffer.h
new file mode 100644 (file)
index 0000000..850c7de
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        secket-buffer.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementatin of MessageBuffer.
+ */
+
+#ifndef _SECURITY_SERVER_SOCKET_BUFFER_
+#define _SECURITY_SERVER_SOCKET_BUFFER_
+
+#include <vector>
+
+#include <dpl/binary_queue.h>
+#include <dpl/exception.h>
+#include <dpl/serialization.h>
+
+namespace SecurityServer {
+
+typedef std::vector<unsigned char> RawBuffer;
+
+class MessageBuffer : public SecurityServer::IStream {
+public:
+    class Exception
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, OutOfData)
+    };
+
+    MessageBuffer()
+      : m_bytesLeft(0)
+    {}
+
+    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);
+
+protected:
+
+    inline void CountBytesLeft() {
+        if (m_bytesLeft > 0)
+            return;  // we already counted m_bytesLeft nothing to do
+
+        if (m_buffer.Size() < sizeof(size_t))
+            return;  // we cannot count m_bytesLeft because buffer is too small
+
+        m_buffer.FlattenConsume(&m_bytesLeft, sizeof(size_t));
+    }
+
+    size_t m_bytesLeft;
+    SecurityServer::BinaryQueue m_buffer;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_SOCKET_BUFFER_
diff --git a/src/server/common/protocols.cpp b/src/server/common/protocols.cpp
new file mode 100644 (file)
index 0000000..06725b7
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        protocols.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       List of all protocols supported by security server.
+ */
+
+#include <protocols.h>
+#include <cstddef>
+
+namespace SecurityServer {
+
+char const * const SERVICE_SOCKET_SHARED_MEMORY =
+    "/tmp/.security-server-api-data-share.sock";
+char const * const SERVICE_SOCKET_ECHO =
+    "/tmp/security-server-api-echo.sock";
+char const * const SERVICE_SOCKET_GET_GID =
+    "/tmp/.security-server-api-get-gid.sock";
+char const * const SERVICE_SOCKET_PRIVILEGE_BY_PID =
+    "/tmp/.security-server-api-privilege-by-pid.sock";
+char const * const SERVICE_SOCKET_GET_OBJECT_NAME =
+    "/tmp/.security-server-api-get-object-name.sock";
+char const * const SERVICE_SOCKET_APP_PERMISSIONS =
+    "/tmp/.security-server-api-app-permissions.sock";
+char const * const SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME =
+    "/tmp/.security-server-api-app-privilege-by-name.sock";
+char const * const SERVICE_SOCKET_COOKIE_GET =
+    "/tmp/.security-server-api-cookie-get.sock";
+char const * const SERVICE_SOCKET_COOKIE_CHECK =
+    "/tmp/.security-server-api-cookie-check.sock";
+//TODO: Merge bellow socket with the one above. This should be done
+//after security-server-api-cookie-check.sock will be protected by smack and has proper label
+char const * const SERVICE_SOCKET_COOKIE_CHECK_TMP =
+    "/tmp/.security-server-api-cookie-check-tmp.sock";
+char const * const SERVICE_SOCKET_OPEN_FOR =
+    "/tmp/.security-server-api-open-for.sock";
+char const * const SERVICE_SOCKET_PASSWD_CHECK =
+    "/tmp/.security-server-api-passwd-check.sock";
+char const * const SERVICE_SOCKET_PASSWD_SET =
+    "/tmp/.security-server-api-passwd-set.sock";
+
+const size_t COOKIE_SIZE = 20;
+
+const size_t MAX_PASSWORD_LEN = 32;
+const unsigned int MAX_PASSWORD_HISTORY = 50;
+
+const int SECURITY_SERVER_MAX_OBJ_NAME         = 30;
+
+} // namespace SecurityServer
+
diff --git a/src/server/common/protocols.h b/src/server/common/protocols.h
new file mode 100644 (file)
index 0000000..7351fca
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        protocols.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This file contains list of all protocols suported by security-sever.
+ */
+
+#ifndef _SECURITY_SERVER_PROTOCOLS_
+#define _SECURITY_SERVER_PROTOCOLS_
+
+#include <cstddef>
+
+namespace SecurityServer {
+
+extern char const * const SERVICE_SOCKET_SHARED_MEMORY;
+extern char const * const SERVICE_SOCKET_ECHO;
+extern char const * const SERVICE_SOCKET_GET_GID;
+extern char const * const SERVICE_SOCKET_PRIVILEGE_BY_PID;
+extern char const * const SERVICE_SOCKET_GET_OBJECT_NAME;
+extern char const * const SERVICE_SOCKET_APP_PERMISSIONS;
+extern char const * const SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME;
+extern char const * const SERVICE_SOCKET_COOKIE_GET;
+extern char const * const SERVICE_SOCKET_COOKIE_CHECK;
+extern char const * const SERVICE_SOCKET_COOKIE_CHECK_TMP;
+extern char const * const SERVICE_SOCKET_OPEN_FOR;
+extern char const * const SERVICE_SOCKET_PASSWD_CHECK;
+extern char const * const SERVICE_SOCKET_PASSWD_SET;
+
+enum class AppPermissionsAction { ENABLE, DISABLE };
+
+enum class CookieCall
+{
+    GET_COOKIE,
+    CHECK_PID,
+    CHECK_SMACKLABEL,
+    CHECK_PRIVILEGE_GID,
+    CHECK_PRIVILEGE,
+    CHECK_GID,
+    CHECK_UID
+};
+
+enum class PrivilegeCheckHdrs
+{
+    CHECK_GIVEN_APP,
+    CHECK_CALLER_APP
+};
+
+extern const size_t COOKIE_SIZE;
+
+enum class PasswordHdrs
+{
+    HDR_IS_PWD_VALID,
+    HDR_CHK_PWD,
+    HDR_SET_PWD,
+    HDR_SET_PWD_VALIDITY,
+    HDR_SET_PWD_MAX_CHALLENGE,
+    HDR_RST_PWD,
+    HDR_SET_PWD_HISTORY
+};
+
+extern const size_t MAX_PASSWORD_LEN;
+extern const unsigned int MAX_PASSWORD_HISTORY;
+
+extern const int SECURITY_SERVER_MAX_OBJ_NAME;
+
+} // namespace SecuritySever
+
+#endif // _SECURITY_SERVER_PROTOCOLS_
+
diff --git a/src/server/common/smack-check.cpp b/src/server/common/smack-check.cpp
new file mode 100644 (file)
index 0000000..0e7bb5a
--- /dev/null
@@ -0,0 +1,34 @@
+#include <smack-check.h>
+
+#include <stdlib.h>
+#include <sys/smack.h>
+
+#include <dpl/log/log.h>
+
+namespace SecurityServer {
+
+int smack_runtime_check(void)
+{
+    static int smack_present = -1;
+    if (-1 == smack_present) {
+        if (NULL == smack_smackfs_path()) {
+            LogDebug("no smack found on device");
+            smack_present = 0;
+        } else {
+            LogDebug("found smack on device");
+            smack_present = 1;
+        }
+    }
+    return smack_present;
+}
+
+int smack_check(void)
+{
+#ifndef SMACK_ENABLED
+    return 0;
+#else
+    return smack_runtime_check();
+#endif
+}
+
+} // namespace SecurityServer
diff --git a/src/server/common/smack-check.h b/src/server/common/smack-check.h
new file mode 100644 (file)
index 0000000..875679c
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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 _SMACK_CHECK_H_
+#define _SMACK_CHECK_H_
+
+namespace SecurityServer {
+
+/*
+ * A very simple runtime check for SMACK on the platform
+ * Returns 1 if SMACK is present, 0 otherwise
+ */
+
+int smack_runtime_check(void);
+
+/*
+ * A very simple runtime check for SMACK on the platform
+ * Returns 1 if SMACK is present, 0 otherwise. If SMACK_ENABLED is not defined
+ * It returns 0.
+ */
+int smack_check(void);
+
+} // namespace SecurityServer
+
+#endif // _SMACK_CHECK_H_
diff --git a/src/server/dpl/core/include/dpl/assert.h b/src/server/dpl/core/include/dpl/assert.h
new file mode 100644 (file)
index 0000000..a71704d
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2011 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        assert.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of assert
+ */
+#ifndef SECURITY_SERVER_ASSERT_H
+#define SECURITY_SERVER_ASSERT_H
+
+#include <dpl/noreturn.h>
+
+namespace SecurityServer {
+// Assertion handler procedure
+// Do not call directly
+// Always use Assert macro
+SECURITYSERVER_NORETURN void AssertProc(const char *condition,
+                             const char *file,
+                             int line,
+                             const char *function);
+} // namespace SecurityServer
+
+#define Assert(Condition) do { if (!(Condition)) { SecurityServer::AssertProc(#Condition, \
+                                                                   __FILE__, \
+                                                                   __LINE__, \
+                                                                   __FUNCTION__); \
+                               } } while (0)
+
+#endif // SECURITY_SERVER_ASSERT_H
diff --git a/src/server/dpl/core/include/dpl/binary_queue.h b/src/server/dpl/core/include/dpl/binary_queue.h
new file mode 100644 (file)
index 0000000..387a71a
--- /dev/null
@@ -0,0 +1,298 @@
+/*
+ * Copyright (c) 2011 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
+ */
+#ifndef SECURITY_SERVER_BINARY_QUEUE_H
+#define SECURITY_SERVER_BINARY_QUEUE_H
+
+//#include <dpl/abstract_input_output.h>
+#include <dpl/exception.h>
+#include <dpl/noncopyable.h>
+#include <memory>
+#include <list>
+
+namespace SecurityServer {
+/**
+ * Binary queue auto pointer
+ */
+class BinaryQueue;
+typedef std::auto_ptr<BinaryQueue> BinaryQueueAutoPtr;
+
+/**
+ * Binary stream implemented as constant size bucket list
+ *
+ * @todo Add optimized implementation for FlattenConsume
+ */
+class BinaryQueue
+//  : public AbstractInputOutput
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, OutOfData)
+    };
+
+    typedef void (*BufferDeleter)(const void *buffer, size_t bufferSize,
+                                  void *userParam);
+    static void BufferDeleterFree(const void *buffer,
+                                  size_t bufferSize,
+                                  void *userParam);
+
+    class BucketVisitor
+    {
+      public:
+        /**
+         * Destructor
+         */
+        virtual ~BucketVisitor();
+
+        /**
+         * Visit bucket
+         *
+         * @return none
+         * @param[in] buffer Constant pointer to bucket data buffer
+         * @param[in] bufferSize Number of bytes in bucket
+         */
+        virtual void OnVisitBucket(const void *buffer, size_t bufferSize) = 0;
+    };
+
+  private:
+    struct Bucket :
+        private Noncopyable
+    {
+        const void *buffer;
+        const void *ptr;
+        size_t size;
+        size_t left;
+
+        BufferDeleter deleter;
+        void *param;
+
+        Bucket(const void *buffer,
+               size_t bufferSize,
+               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);
+
+    /**
+     * 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);
+
+    /**
+     * Append copy of @a bufferSize 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] bufferSize 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 bufferSize);
+
+    /**
+     * Append @a bufferSize 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] bufferSize 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 bufferSize,
+        BufferDeleter deleter =
+            &BinaryQueue::BufferDeleterFree,
+        void *userParam = NULL);
+
+    /**
+     * 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 bufferSize 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] bufferSize 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 bufferSize) const;
+
+    /**
+     * Retrieve @a bufferSize 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] bufferSize 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 bufferSize);
+
+    /**
+     * 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;
+
+    /**
+     * IAbstractInput interface
+     */
+    virtual BinaryQueueAutoPtr Read(size_t size);
+
+    /**
+     * IAbstractOutput interface
+     */
+    virtual size_t Write(const BinaryQueue &buffer, size_t bufferSize);
+};
+
+} // namespace SecurityServer
+
+#endif // SECURITY_SERVER_BINARY_QUEUE_H
diff --git a/src/server/dpl/core/include/dpl/colors.h b/src/server/dpl/core/include/dpl/colors.h
new file mode 100644 (file)
index 0000000..37ce940
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 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        colors.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Some constants with definition of colors for Console
+ *              and html output
+ */
+
+#ifndef SECURITY_SERVER_COLORS_H
+#define SECURITY_SERVER_COLORS_H
+
+namespace SecurityServer {
+namespace Colors {
+namespace Text {
+extern const char* BOLD_GREEN_BEGIN;
+extern const char* BOLD_GREEN_END;
+extern const char* PURPLE_BEGIN;
+extern const char* PURPLE_END;
+extern const char* RED_BEGIN;
+extern const char* RED_END;
+extern const char* GREEN_BEGIN;
+extern const char* GREEN_END;
+extern const char* CYAN_BEGIN;
+extern const char* CYAN_END;
+extern const char* BOLD_RED_BEGIN;
+extern const char* BOLD_RED_END;
+extern const char* BOLD_YELLOW_BEGIN;
+extern const char* BOLD_YELLOW_END;
+extern const char* BOLD_GOLD_BEGIN;
+extern const char* BOLD_GOLD_END;
+extern const char* BOLD_WHITE_BEGIN;
+extern const char* BOLD_WHITE_END;
+} //namespace Text
+
+namespace Html {
+extern const char* BOLD_GREEN_BEGIN;
+extern const char* BOLD_GREEN_END;
+extern const char* PURPLE_BEGIN;
+extern const char* PURPLE_END;
+extern const char* RED_BEGIN;
+extern const char* RED_END;
+extern const char* GREEN_BEGIN;
+extern const char* GREEN_END;
+extern const char* CYAN_BEGIN;
+extern const char* CYAN_END;
+extern const char* BOLD_RED_BEGIN;
+extern const char* BOLD_RED_END;
+extern const char* BOLD_YELLOW_BEGIN;
+extern const char* BOLD_YELLOW_END;
+extern const char* BOLD_GOLD_BEGIN;
+extern const char* BOLD_GOLD_END;
+extern const char* BOLD_WHITE_BEGIN;
+extern const char* BOLD_WHITE_END;
+} //namespace Html
+} //namespace Colors
+} //namespace SecurityServer
+
+#endif /* SECURITY_SERVER_COLORS_H */
diff --git a/src/server/dpl/core/include/dpl/exception.h b/src/server/dpl/core/include/dpl/exception.h
new file mode 100644 (file)
index 0000000..ff8d300
--- /dev/null
@@ -0,0 +1,385 @@
+/*
+ * Copyright (c) 2011 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    exception.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version 1.0
+ * @brief   Header file for base exception
+ */
+#ifndef SECURITY_SERVER_EXCEPTION_H
+#define SECURITY_SERVER_EXCEPTION_H
+
+#include <string>
+#include <cstring>
+#include <cstdio>
+#include <exception>
+#include <cstdlib>
+#include <sstream>
+
+namespace SecurityServer {
+void LogUnhandledException(const std::string &str);
+void LogUnhandledException(const std::string &str,
+                           const char *filename,
+                           int line,
+                           const char *function);
+}
+
+namespace SecurityServer {
+class Exception
+{
+  private:
+    static unsigned int m_exceptionCount;
+    static Exception* m_lastException;
+    static void (*m_terminateHandler)();
+
+    static void AddRef(Exception* exception)
+    {
+        if (!m_exceptionCount) {
+            m_terminateHandler = std::set_terminate(&TerminateHandler);
+        }
+
+        ++m_exceptionCount;
+        m_lastException = exception;
+    }
+
+    static void UnRef(Exception* e)
+    {
+        if (m_lastException == e) {
+            m_lastException = NULL;
+        }
+
+        --m_exceptionCount;
+
+        if (!m_exceptionCount) {
+            std::set_terminate(m_terminateHandler);
+            m_terminateHandler = NULL;
+        }
+    }
+
+    static void TerminateHandler()
+    {
+        if (m_lastException != NULL) {
+            DisplayKnownException(*m_lastException);
+            abort();
+        } else {
+            DisplayUnknownException();
+            abort();
+        }
+    }
+
+    Exception *m_reason;
+    std::string m_path;
+    std::string m_function;
+    int m_line;
+
+  protected:
+    std::string m_message;
+    std::string m_className;
+
+  public:
+    static std::string KnownExceptionToString(const Exception &e)
+    {
+        std::ostringstream message;
+        message <<
+        "\033[1;5;31m\n=== Unhandled SecurityServer exception occurred ===\033[m\n\n";
+        message << "\033[1;33mException trace:\033[m\n\n";
+        message << e.DumpToString();
+        message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+
+        return message.str();
+    }
+
+    static std::string UnknownExceptionToString()
+    {
+        std::ostringstream message;
+        message <<
+        "\033[1;5;31m\n=== Unhandled non-SecurityServer exception occurred ===\033[m\n\n";
+        message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+
+        return message.str();
+    }
+
+    static void DisplayKnownException(const Exception& e)
+    {
+        LogUnhandledException(KnownExceptionToString(e).c_str());
+    }
+
+    static void DisplayUnknownException()
+    {
+        LogUnhandledException(UnknownExceptionToString().c_str());
+    }
+
+    Exception(const Exception &other)
+    {
+        // Deep copy
+        if (other.m_reason != NULL) {
+            m_reason = new Exception(*other.m_reason);
+        } else {
+            m_reason = NULL;
+        }
+
+        m_message = other.m_message;
+        m_path = other.m_path;
+        m_function = other.m_function;
+        m_line = other.m_line;
+
+        m_className = other.m_className;
+
+        AddRef(this);
+    }
+
+    const Exception &operator =(const Exception &other)
+    {
+        if (this == &other) {
+            return *this;
+        }
+
+        // Deep copy
+        if (other.m_reason != NULL) {
+            m_reason = new Exception(*other.m_reason);
+        } else {
+            m_reason = NULL;
+        }
+
+        m_message = other.m_message;
+        m_path = other.m_path;
+        m_function = other.m_function;
+        m_line = other.m_line;
+
+        m_className = other.m_className;
+
+        AddRef(this);
+
+        return *this;
+    }
+
+    Exception(const char *path,
+              const char *function,
+              int line,
+              const std::string &message) :
+        m_reason(NULL),
+        m_path(path),
+        m_function(function),
+        m_line(line),
+        m_message(message)
+    {
+        AddRef(this);
+    }
+
+    Exception(const char *path,
+              const char *function,
+              int line,
+              const Exception &reason,
+              const std::string &message) :
+        m_reason(new Exception(reason)),
+        m_path(path),
+        m_function(function),
+        m_line(line),
+        m_message(message)
+    {
+        AddRef(this);
+    }
+
+    virtual ~Exception() throw()
+    {
+        if (m_reason != NULL) {
+            delete m_reason;
+            m_reason = NULL;
+        }
+
+        UnRef(this);
+    }
+
+    void Dump() const
+    {
+        // Show reason first
+        if (m_reason != NULL) {
+            m_reason->Dump();
+        }
+
+        // Afterward, dump exception
+        const char *file = strchr(m_path.c_str(), '/');
+
+        if (file == NULL) {
+            file = m_path.c_str();
+        } else {
+            ++file;
+        }
+
+        printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+               file, m_line,
+               m_function.c_str(),
+               m_className.c_str(),
+               m_message.empty() ? "<EMPTY>" : m_message.c_str());
+    }
+
+    std::string DumpToString() const
+    {
+        std::string ret;
+        if (m_reason != NULL) {
+            ret = m_reason->DumpToString();
+        }
+
+        const char *file = strchr(m_path.c_str(), '/');
+
+        if (file == NULL) {
+            file = m_path.c_str();
+        } else {
+            ++file;
+        }
+
+        char buf[1024];
+        snprintf(buf,
+                 sizeof(buf),
+                 "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+                 file,
+                 m_line,
+                 m_function.c_str(),
+                 m_className.c_str(),
+                 m_message.empty() ? "<EMPTY>" : m_message.c_str());
+
+        buf[sizeof(buf) - 1] = '\n';
+        ret += buf;
+
+        return ret;
+    }
+
+    Exception *GetReason() const
+    {
+        return m_reason;
+    }
+
+    std::string GetPath() const
+    {
+        return m_path;
+    }
+
+    std::string GetFunction() const
+    {
+        return m_function;
+    }
+
+    int GetLine() const
+    {
+        return m_line;
+    }
+
+    std::string GetMessage() const
+    {
+        return m_message;
+    }
+
+    std::string GetClassName() const
+    {
+        return m_className;
+    }
+};
+} // namespace SecurityServer
+
+#define Try try
+
+#define Throw(ClassName) \
+    throw ClassName(__FILE__, __FUNCTION__, __LINE__)
+
+#define ThrowMsg(ClassName, Message)                                                 \
+    do                                                                               \
+    {                                                                                \
+        std::ostringstream dplLoggingStream;                                         \
+        dplLoggingStream << Message;                                                 \
+        throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str());   \
+    } while (0)
+
+#define ReThrow(ClassName) \
+    throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
+
+#define ReThrowMsg(ClassName, Message) \
+    throw ClassName(__FILE__, \
+                    __FUNCTION__, \
+                    __LINE__, \
+                    _rethrown_exception, \
+                    Message)
+
+#define Catch(ClassName) \
+    catch (const ClassName &_rethrown_exception)
+
+#define DECLARE_EXCEPTION_TYPE(BaseClass, Class)                                                                                          \
+    class Class :                                                                                                                                 \
+        public BaseClass                                                                                                                \
+    {                                                                                                                                     \
+      public:                                                                                                                               \
+        Class(const char *path, \
+              const char *function, \
+              int line, \
+              const std::string & message = std::string()) :                                                                                                                             \
+            BaseClass(path, function, line, message)                                                                                    \
+        {                                                                                                                                 \
+            BaseClass::m_className = #Class;                                                                                              \
+        }                                                                                                                                 \
+                                                                                                                                          \
+        Class(const char *path, \
+              const char *function, \
+              int line, \
+              const SecurityServer::Exception & reason, \
+              const std::string & message = std::string()) :                                                                                                                             \
+            BaseClass(path, function, line, reason, message)                                                                            \
+        {                                                                                                                                 \
+            BaseClass::m_className = #Class;                                                                                              \
+        }                                                                                                                                 \
+    };
+
+#define UNHANDLED_EXCEPTION_HANDLER_BEGIN try
+
+#define UNHANDLED_EXCEPTION_HANDLER_END                                                                   \
+    catch (const SecurityServer::Exception &exception)                                                               \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << SecurityServer::Exception::KnownExceptionToString(exception);                                         \
+        SecurityServer::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }                                                                                                     \
+    catch (std::exception& e)                                                                             \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << e.what();                                                                                  \
+        msg << "\n";                                                                                      \
+        msg << SecurityServer::Exception::UnknownExceptionToString();                                                \
+        SecurityServer::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }                                                                                                     \
+    catch (...)                                                                                           \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << SecurityServer::Exception::UnknownExceptionToString();                                                \
+        SecurityServer::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }
+
+namespace SecurityServer {
+namespace CommonException {
+/**
+ * Internal exception definitions
+ *
+ * These should normally not happen.
+ * Usually, exception trace with internal error includes
+ * important messages.
+ */
+DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
+                                                 // underlying libraries or
+                                                 // kernel
+}
+}
+
+#endif // SECURITY_SERVER_EXCEPTION_H
diff --git a/src/server/dpl/core/include/dpl/noncopyable.h b/src/server/dpl/core/include/dpl/noncopyable.h
new file mode 100644 (file)
index 0000000..dae75e8
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 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        noncopyable
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of noncopyable
+ */
+#ifndef SECURITYSERVER_NONCOPYABLE_H
+#define SECURITYSERVER_NONCOPYABLE_H
+
+namespace SecurityServer {
+class Noncopyable
+{
+  private:
+    Noncopyable(const Noncopyable &);
+    const Noncopyable &operator=(const Noncopyable &);
+
+  public:
+    Noncopyable();
+    virtual ~Noncopyable();
+};
+} // namespace SecurityServer
+
+#endif // SECURITYSERVER_NONCOPYABLE_H
diff --git a/src/server/dpl/core/include/dpl/noreturn.h b/src/server/dpl/core/include/dpl/noreturn.h
new file mode 100644 (file)
index 0000000..44dfd4a
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 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        noreturn.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of noreturn
+ */
+#ifndef SECURITYSERVER_NORETURN_H
+#define SECURITYSERVER_NORETURN_H
+
+#define SECURITYSERVER_NORETURN __attribute__((__noreturn__))
+
+#endif // SECURITYSERVER_NORETURN_H
diff --git a/src/server/dpl/core/include/dpl/serialization.h b/src/server/dpl/core/include/dpl/serialization.h
new file mode 100644 (file)
index 0000000..5c2a0ff
--- /dev/null
@@ -0,0 +1,390 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+#ifndef SERIALIZATION_H
+#define SERIALIZATION_H
+
+#include <string>
+#include <vector>
+#include <list>
+#include <map>
+
+namespace SecurityServer {
+// 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 int
+    static void Serialize(IStream& stream, const unsigned value)
+    {
+        stream.Write(sizeof(value), &value);
+    }
+    static void Serialize(IStream& stream, const unsigned* const value)
+    {
+        stream.Write(sizeof(*value), value);
+    }
+
+    // int
+    static void Serialize(IStream& stream, const int value)
+    {
+        stream.Write(sizeof(value), &value);
+    }
+    static void Serialize(IStream& stream, const int* 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);
+    }
+
+    // time_t
+    static void Serialize(IStream& stream, const time_t value)
+    {
+        stream.Write(sizeof(value), &value);
+    }
+    static void Serialize(IStream& stream, const time_t* const value)
+    {
+        stream.Write(sizeof(*value), value);
+    }
+
+    // std::string
+    static void Serialize(IStream& stream, const std::string& str)
+    {
+        int length = str.size();
+        stream.Write(sizeof(length), &length);
+        stream.Write(length, str.c_str());
+    }
+    static void Serialize(IStream& stream, const std::string* const str)
+    {
+        int length = str->size();
+        stream.Write(sizeof(length), &length);
+        stream.Write(length, str->c_str());
+    }
+
+    // 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);
+    }
+
+    // std::vector
+    template <typename T>
+    static void Serialize(IStream& stream, const std::vector<T>& vec)
+    {
+        int length = vec.size();
+        stream.Write(sizeof(length), &length);
+        for (typename std::vector<T>::const_iterator vec_iter = vec.begin();
+             vec_iter != vec.end(); vec_iter++)
+        {
+            Serialize(stream, *vec_iter);
+        }
+    }
+    template <typename T>
+    static void Serialize(IStream& stream, const std::vector<T>* 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);
+    }
+}; // 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 int
+    static void Deserialize(IStream& stream, unsigned& value)
+    {
+        stream.Read(sizeof(value), &value);
+    }
+    static void Deserialize(IStream& stream, unsigned*& value)
+    {
+        value = new unsigned;
+        stream.Read(sizeof(*value), value);
+    }
+
+    // int
+    static void Deserialize(IStream& stream, int& value)
+    {
+        stream.Read(sizeof(value), &value);
+    }
+    static void Deserialize(IStream& stream, int*& value)
+    {
+        value = new int;
+        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);
+    }
+
+    // time_t
+    static void Deserialize(IStream& stream, time_t& value)
+    {
+        stream.Read(sizeof(value), &value);
+    }
+    static void Deserialize(IStream& stream, time_t*& value)
+    {
+        value = new time_t;
+        stream.Read(sizeof(*value), value);
+    }
+
+    // std::string
+    static void Deserialize(IStream& stream, std::string& str)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        char * buf = new char[length + 1];
+        stream.Read(length, buf);
+        buf[length] = 0;
+        str = std::string(buf);
+        delete[] buf;
+    }
+    static void Deserialize(IStream& stream, std::string*& str)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        char * buf = new char[length + 1];
+        stream.Read(length, buf);
+        buf[length] = 0;
+        str = new std::string(buf);
+        delete[] buf;
+    }
+
+    // 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(obj);
+        }
+    }
+    template <typename T>
+    static void Deserialize(IStream& stream, std::list<T>*& list)
+    {
+        list = new std::list<T>;
+        Deserialize(stream, *list);
+    }
+
+    // std::vector
+    template <typename T>
+    static void Deserialize(IStream& stream, std::vector<T>& vec)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        for (int i = 0; i < length; ++i) {
+            T obj;
+            Deserialize(stream, obj);
+            vec.push_back(obj);
+        }
+    }
+    template <typename T>
+    static void Deserialize(IStream& stream, std::vector<T>*& vec)
+    {
+        vec = new std::vector<T>;
+        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] = 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
+} // namespace SecurityServer
+
+#endif // SERIALIZATION_H
diff --git a/src/server/dpl/core/include/dpl/singleton.h b/src/server/dpl/core/include/dpl/singleton.h
new file mode 100644 (file)
index 0000000..b46104f
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2011 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        singleton.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef SECURITYSERVER_SINGLETON_H
+#define SECURITYSERVER_SINGLETON_H
+
+namespace SecurityServer {
+template<typename Class>
+class Singleton :
+    private Class
+{
+    //
+    // Note:
+    //
+    // To remove posibility of instantiating directly Class,
+    // make Class' default constructor protected
+    //
+
+  private:
+    Singleton()
+    {}
+
+    static Singleton &InternalInstance();
+
+  public:
+    virtual ~Singleton()
+    {}
+
+    static Class &Instance();
+};
+} // namespace SecurityServer
+
+#endif // SECURITYSERVER_SINGLETON_H
diff --git a/src/server/dpl/core/include/dpl/singleton_impl.h b/src/server/dpl/core/include/dpl/singleton_impl.h
new file mode 100644 (file)
index 0000000..31c054f
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2011 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        singleton_impl.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef SECURITYSERVER_SINGLETON_IMPL_H
+#define SECURITYSERVER_SINGLETON_IMPL_H
+
+/*
+ * WARNING!
+ *
+ * If some singleton's implementation uses another singletons implementation,
+ * those templates make the second singleton a dubleton. Be warned. Try to use
+ * singleton_safe_impl.h if possible.
+ */
+
+namespace SecurityServer {
+template<typename Class>
+Singleton<Class>& Singleton<Class>::InternalInstance()
+{
+    static Singleton<Class> instance;
+    return instance;
+}
+
+template<typename Class>
+Class &Singleton<Class>::Instance()
+{
+    Singleton<Class>& instance = Singleton<Class>::InternalInstance();
+    return instance;
+}
+} // namespace SecurityServer
+
+#define IMPLEMENT_SINGLETON(Type)                                           \
+    template SecurityServer::Singleton<Type>&SecurityServer::Singleton<Type>::InternalInstance();    \
+    template Type & SecurityServer::Singleton<Type>::Instance();                            \
+
+#endif // SECURITYSERVER_SINGLETON_IMPL_H
diff --git a/src/server/dpl/core/include/dpl/singleton_safe_impl.h b/src/server/dpl/core/include/dpl/singleton_safe_impl.h
new file mode 100644 (file)
index 0000000..abef281
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 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        singleton_safe_impl.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef SECURITYSERVER_SINGLETON_SAFE_IMPL_H
+#define SECURITYSERVER_SINGLETON_SAFE_IMPL_H
+
+#define IMPLEMENT_SAFE_SINGLETON(Class)                                        \
+    namespace SecurityServer {                                                                \
+    template<>                                                                     \
+    Singleton<Class>&Singleton<Class>::InternalInstance()                         \
+    {                                                                              \
+        static Singleton<Class> instance;                                          \
+        return instance;                                                           \
+    }                                                                              \
+                                                                               \
+    template<>                                                                     \
+    Class & Singleton<Class>::Instance()                                            \
+    {                                                                              \
+        Singleton<Class>& instance = Singleton<Class>::InternalInstance();         \
+        return instance;                                                           \
+    }                                                                              \
+                                                                               \
+    template Singleton<Class>&Singleton<Class>::InternalInstance();               \
+    template Class & Singleton<Class>::Instance();                                  \
+    } // namespace SecurityServer
+
+#endif // SECURITYSERVER_SINGLETON_SAFE_IMPL_H
diff --git a/src/server/dpl/core/src/assert.cpp b/src/server/dpl/core/src/assert.cpp
new file mode 100644 (file)
index 0000000..440b03a
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2011 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        assert.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of assert
+ */
+#include <stddef.h>
+#include <dpl/assert.h>
+#include <dpl/colors.h>
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+#include <cstdlib>
+
+namespace SecurityServer {
+void AssertProc(const char *condition,
+                const char *file,
+                int line,
+                const char *function)
+{
+#define INTERNAL_LOG(message)                                          \
+    do                                                                 \
+    {                                                                  \
+        std::ostringstream platformLog;                                \
+        platformLog << message;                                        \
+        SecurityServer::Log::LogSystemSingleton::Instance().Pedantic(             \
+            platformLog.str().c_str(),                                 \
+            __FILE__, __LINE__, __FUNCTION__);                         \
+    } \
+    while (0)
+
+    // Try to log failed assertion to log system
+    Try
+    {
+        INTERNAL_LOG(
+            "################################################################################");
+        INTERNAL_LOG(
+            "###                          SecurityServer assertion failed!                           ###");
+        INTERNAL_LOG(
+            "################################################################################");
+        INTERNAL_LOG("### Condition: " << condition);
+        INTERNAL_LOG("### File: " << file);
+        INTERNAL_LOG("### Line: " << line);
+        INTERNAL_LOG("### Function: " << function);
+        INTERNAL_LOG(
+            "################################################################################");
+    } catch (Exception) {
+        // Just ignore possible double errors
+    }
+
+    // Fail with c-library abort
+    abort();
+}
+} // namespace SecurityServer
diff --git a/src/server/dpl/core/src/binary_queue.cpp b/src/server/dpl/core/src/binary_queue.cpp
new file mode 100644 (file)
index 0000000..be0c65d
--- /dev/null
@@ -0,0 +1,317 @@
+/*
+ * Copyright (c) 2011 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       This file is the implementation file of binary queue
+ */
+#include <stddef.h>
+#include <dpl/binary_queue.h>
+#include <dpl/assert.h>
+#include <algorithm>
+#include <malloc.h>
+#include <cstring>
+#include <new>
+
+namespace SecurityServer {
+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 == NULL) {
+        throw std::bad_alloc();
+    }
+
+    try {
+        other.Flatten(bufferCopy, other.m_size);
+        AppendUnmanaged(bufferCopy, other.m_size, &BufferDeleterFree, NULL);
+    } 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 bufferSize)
+{
+    // Create data copy with malloc/free
+    void *bufferCopy = malloc(bufferSize);
+
+    // Check if allocation succeded
+    if (bufferCopy == NULL) {
+        throw std::bad_alloc();
+    }
+
+    // Copy user data
+    memcpy(bufferCopy, buffer, bufferSize);
+
+    try {
+        // Try to append new bucket
+        AppendUnmanaged(bufferCopy, bufferSize, &BufferDeleterFree, NULL);
+    } catch (const std::bad_alloc &) {
+        // Free allocated memory
+        free(bufferCopy);
+        throw;
+    }
+}
+
+void BinaryQueue::AppendUnmanaged(const void* buffer,
+                                  size_t bufferSize,
+                                  BufferDeleter deleter,
+                                  void* userParam)
+{
+    // Do not attach empty buckets
+    if (bufferSize == 0) {
+        deleter(buffer, bufferSize, userParam);
+        return;
+    }
+
+    // Just add new bucket with selected deleter
+    Bucket *bucket = new Bucket(buffer, bufferSize, deleter, userParam);
+    try {
+        m_buckets.push_back(bucket);
+    } catch (const std::bad_alloc &) {
+        delete bucket;
+        throw;
+    }
+
+    // Increase total queue size
+    m_size += bufferSize;
+}
+
+size_t BinaryQueue::Size() const
+{
+    return m_size;
+}
+
+bool BinaryQueue::Empty() const
+{
+    return m_size == 0;
+}
+
+void BinaryQueue::Consume(size_t size)
+{
+    // Check parameters
+    if (size > m_size) {
+        Throw(Exception::OutOfData);
+    }
+
+    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 bufferSize) const
+{
+    // Check parameters
+    if (bufferSize == 0) {
+        return;
+    }
+
+    if (bufferSize > m_size) {
+        Throw(Exception::OutOfData);
+    }
+
+    size_t bytesLeft = bufferSize;
+    void *ptr = buffer;
+    BucketList::const_iterator bucketIterator = m_buckets.begin();
+    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 bufferSize)
+{
+    // FIXME: Optimize
+    Flatten(buffer, bufferSize);
+    Consume(bufferSize);
+}
+
+void BinaryQueue::DeleteBucket(BinaryQueue::Bucket *bucket)
+{
+    delete bucket;
+}
+
+void BinaryQueue::BufferDeleterFree(const void* data,
+                                    size_t dataSize,
+                                    void* userParam)
+{
+    (void)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)
+{
+    Assert(data != NULL);
+    Assert(deleter != NULL);
+}
+
+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
+{
+    Assert(visitor != NULL);
+
+    // Visit all buckets
+    std::for_each(m_buckets.begin(), m_buckets.end(), BucketVisitorCall(visitor));
+}
+
+BinaryQueueAutoPtr BinaryQueue::Read(size_t size)
+{
+    // Simulate input stream
+    size_t available = std::min(size, m_size);
+
+    std::unique_ptr<void, std::function<void(void*)>>
+        bufferCopy(malloc(available), free);
+
+    if (!bufferCopy.get()) {
+        throw std::bad_alloc();
+    }
+
+    BinaryQueueAutoPtr result(new BinaryQueue());
+
+    Flatten(bufferCopy.get(), available);
+    result->AppendUnmanaged(
+        bufferCopy.release(), available, &BufferDeleterFree, NULL);
+    Consume(available);
+
+    return result;
+}
+
+size_t BinaryQueue::Write(const BinaryQueue &buffer, size_t bufferSize)
+{
+    // Simulate output stream
+    AppendCopyFrom(buffer);
+    return bufferSize;
+}
+} // namespace SecurityServer
diff --git a/src/server/dpl/core/src/colors.cpp b/src/server/dpl/core/src/colors.cpp
new file mode 100644 (file)
index 0000000..6563a26
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2011 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        colors.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Some constants with definition of colors for Console
+ *              and html output
+ */
+#include <stddef.h>
+#include <dpl/colors.h>
+
+namespace SecurityServer {
+namespace Colors {
+namespace Text {
+const char* BOLD_GREEN_BEGIN = "\033[1;32m";
+const char* BOLD_GREEN_END = "\033[m";
+const char* RED_BEGIN = "\033[0;31m";
+const char* RED_END = "\033[m";
+const char* PURPLE_BEGIN = "\033[0;35m";
+const char* PURPLE_END = "\033[m";
+const char* GREEN_BEGIN = "\033[0;32m";
+const char* GREEN_END = "\033[m";
+const char* CYAN_BEGIN = "\033[0;36m";
+const char* CYAN_END = "\033[m";
+const char* BOLD_RED_BEGIN = "\033[1;31m";
+const char* BOLD_RED_END = "\033[m";
+const char* BOLD_YELLOW_BEGIN = "\033[1;33m";
+const char* BOLD_YELLOW_END = "\033[m";
+const char* BOLD_GOLD_BEGIN = "\033[0;33m";
+const char* BOLD_GOLD_END = "\033[m";
+const char* BOLD_WHITE_BEGIN = "\033[1;37m";
+const char* BOLD_WHITE_END = "\033[m";
+} //namespace Text
+
+namespace Html {
+const char* BOLD_GREEN_BEGIN = "<font color=\"green\"><b>";
+const char* BOLD_GREEN_END = "</b></font>";
+const char* PURPLE_BEGIN = "<font color=\"purple\"><b>";
+const char* PURPLE_END = "</b></font>";
+const char* RED_BEGIN = "<font color=\"red\"><b>";
+const char* RED_END = "</b></font>";
+const char* GREEN_BEGIN = "<font color=\"green\">";
+const char* GREEN_END = "</font>";
+const char* CYAN_BEGIN = "<font color=\"cyan\">";
+const char* CYAN_END = "</font>";
+const char* BOLD_RED_BEGIN = "<font color=\"red\"><b>";
+const char* BOLD_RED_END = "</b></font>";
+const char* BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>";
+const char* BOLD_YELLOW_END = "</b></font>";
+const char* BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>";
+const char* BOLD_GOLD_END = "</b></font>";
+const char* BOLD_WHITE_BEGIN = "<font color=\"white\"><b>";
+const char* BOLD_WHITE_END = "</b></font>";
+} //namespace Html
+} //namespace Colors
+} //namespace SecurityServer
diff --git a/src/server/dpl/core/src/exception.cpp b/src/server/dpl/core/src/exception.cpp
new file mode 100644 (file)
index 0000000..d1635bc
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2011 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        exception.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation of exception system
+ */
+#include <stddef.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+#include <cstdio>
+
+namespace SecurityServer {
+Exception* Exception::m_lastException = NULL;
+unsigned int Exception::m_exceptionCount = 0;
+void (*Exception::m_terminateHandler)() = NULL;
+
+void LogUnhandledException(const std::string &str)
+{
+    // Logging to console
+    printf("%s\n", str.c_str());
+
+    // Logging to dlog
+    LogPedantic(str);
+}
+
+void LogUnhandledException(const std::string &str,
+                           const char *filename,
+                           int line,
+                           const char *function)
+{
+    // Logging to console
+    std::ostringstream msg;
+    msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " <<
+    function << " ===\033[m";
+    msg << str;
+    printf("%s\n", msg.str().c_str());
+
+    // Logging to dlog
+    SecurityServer::Log::LogSystemSingleton::Instance().Error(
+        str.c_str(), filename, line, function);
+}
+} // namespace SecurityServer
diff --git a/src/server/dpl/core/src/noncopyable.cpp b/src/server/dpl/core/src/noncopyable.cpp
new file mode 100644 (file)
index 0000000..c58e25a
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 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        noncopyable.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of noncopyable
+ */
+#include <stddef.h>
+#include <dpl/noncopyable.h>
+
+namespace SecurityServer {
+Noncopyable::Noncopyable()
+{}
+
+Noncopyable::~Noncopyable()
+{}
+} // namespace SecurityServer
diff --git a/src/server/dpl/core/src/serialization.cpp b/src/server/dpl/core/src/serialization.cpp
new file mode 100644 (file)
index 0000000..f8f05ff
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 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.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of data serialization.
+ */
+#include <stddef.h>
+#include <dpl/serialization.h>
+
+//
+// Note:
+//
+// The file here is left blank to enable precompilation
+// of templates in corresponding header file.
+// Do not remove this file.
+//
diff --git a/src/server/dpl/core/src/singleton.cpp b/src/server/dpl/core/src/singleton.cpp
new file mode 100644 (file)
index 0000000..a76e8ac
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 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        generic_event.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#include <stddef.h>
+#include <dpl/singleton.h>
+
+//
+// Note:
+//
+// The file here is left blank to enable precompilation
+// of templates in corresponding header file.
+// Do not remove this file.
+//
diff --git a/src/server/dpl/log/include/dpl/log/abstract_log_provider.h b/src/server/dpl/log/include/dpl/log/abstract_log_provider.h
new file mode 100644 (file)
index 0000000..7679924
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2011 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        abstract_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of abstract log provider
+ */
+#ifndef SECURITYSERVER_ABSTRACT_LOG_PROVIDER_H
+#define SECURITYSERVER_ABSTRACT_LOG_PROVIDER_H
+
+namespace SecurityServer {
+namespace Log {
+class AbstractLogProvider
+{
+  public:
+    virtual ~AbstractLogProvider() {}
+
+    virtual void SetTag(const char *tag);
+
+    virtual void Debug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function) = 0;
+    virtual void Info(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function) = 0;
+    virtual void Warning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function) = 0;
+    virtual void Error(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function) = 0;
+    virtual void Pedantic(const char *message,
+                          const char *fileName,
+                          int line,
+                          const char *function) = 0;
+    virtual void SecureDebug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function) = 0;
+    virtual void SecureInfo(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function) = 0;
+    virtual void SecureWarning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function) = 0;
+    virtual void SecureError(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function) = 0;
+    virtual void SmackAudit(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function) = 0;
+
+  protected:
+    static const char *LocateSourceFileName(const char *filename);
+};
+}
+} // namespace SecurityServer
+
+#endif // SECURITYSERVER_ABSTRACT_LOG_PROVIDER_H
diff --git a/src/server/dpl/log/include/dpl/log/audit-smack-log.h b/src/server/dpl/log/include/dpl/log/audit-smack-log.h
new file mode 100644 (file)
index 0000000..912ad53
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        audit-smack-log.h
+ * @author      Marek Smolinski (m.smolinski@samsung.com)
+ * @version     1.0
+ * @brief       AuditSmackLog loging SMACK access deny sequentially into files
+ */
+
+#ifndef _AUDIT_SMACK_LOG_
+#define _AUDIT_SMACK_LOG_
+
+#include <dpl/log/abstract_log_provider.h>
+
+#include <map>
+#include <fstream>
+#include <mutex>
+#include <memory>
+#include <functional>
+
+namespace SecurityServer {
+namespace Log {
+
+class AuditSmackLog :
+    public AbstractLogProvider
+{
+public:
+    AuditSmackLog();
+    virtual ~AuditSmackLog();
+
+    bool Fail() const;
+
+    virtual void Debug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Info(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+    virtual void Warning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function);
+    virtual void Error(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Pedantic(const char *message,
+                          const char *fileName,
+                          int line,
+                          const char *function);
+    virtual void SecureDebug(const char *message,
+                             const char *fileName,
+                             int line,
+                             const char *function);
+    virtual void SecureInfo(const char *message,
+                            const char *fileName,
+                            int line,
+                            const char *function);
+    virtual void SecureWarning(const char *message,
+                              const char *fileName,
+                              int line,
+                              const char *function);
+    virtual void SecureError(const char *message,
+                             const char *fileName,
+                             int line,
+                             const char *function);
+
+    virtual void SmackAudit(const char *message,
+                            const char *fileName,
+                            int line,
+                            const char *function);
+
+private:
+    void HandleWrite(const char *message,
+                     const char *fileName,
+                     int line,
+                     const char *function);
+
+    int CreateLogFile();
+    int RemoveOldestLogFile();
+    int ParseConfig();
+    int ProcessLogDir();
+    bool IsFileFull(std::ofstream &fs) const;
+
+    bool m_state;
+    unsigned int m_filesCount;
+    unsigned int m_fileMaxBytesSize;
+
+    std::map<time_t, std::string> m_fileNameMap;
+    std::ofstream m_outputStream;
+
+    std::mutex m_writeMtx;
+};
+
+}  // namespace Log
+}  // namespace SecurityServer
+#endif  // _AUDIT_SMACK_LOG_
diff --git a/src/server/dpl/log/include/dpl/log/dlog_log_provider.h b/src/server/dpl/log/include/dpl/log/dlog_log_provider.h
new file mode 100644 (file)
index 0000000..cd76c46
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2011 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_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of DLOG log provider
+ */
+#ifndef SECURITYSERVER_DLOG_LOG_PROVIDER_H
+#define SECURITYSERVER_DLOG_LOG_PROVIDER_H
+
+#include <dpl/log/abstract_log_provider.h>
+#include <memory>
+#include <string>
+
+namespace SecurityServer {
+namespace Log {
+class DLOGLogProvider :
+    public AbstractLogProvider
+{
+  private:
+    std::unique_ptr<char[]> m_tag;
+
+    static std::string FormatMessage(const char *message,
+                                     const char *filename,
+                                     int line,
+                                     const char *function);
+
+  public:
+    DLOGLogProvider();
+    virtual ~DLOGLogProvider();
+
+    virtual void Debug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Info(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+    virtual void Warning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function);
+    virtual void Error(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Pedantic(const char *message,
+                          const char *fileName,
+                          int line,
+                          const char *function);
+    virtual void SecureDebug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void SecureInfo(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+    virtual void SecureWarning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function);
+    virtual void SecureError(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void SmackAudit(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+
+    // Set global Tag according to DLOG
+    void SetTag(const char *tag);
+};
+
+} // namespace Log
+} // namespace SecurityServer
+
+#endif // SECURITYSERVER_DLOG_LOG_PROVIDER_H
diff --git a/src/server/dpl/log/include/dpl/log/log.h b/src/server/dpl/log/include/dpl/log/log.h
new file mode 100644 (file)
index 0000000..9d8403a
--- /dev/null
@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 2011 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.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of log system
+ */
+#ifndef SECURITYSERVER_LOG_H
+#define SECURITYSERVER_LOG_H
+
+#include <dpl/singleton.h>
+#include <dpl/noncopyable.h>
+#include <dpl/log/abstract_log_provider.h>
+#include <sstream>
+#include <list>
+
+namespace SecurityServer {
+namespace Log {
+/**
+ * SecurityServer log system
+ *
+ * To switch logs into old style, export
+ * DPL_USE_OLD_STYLE_LOGS before application start
+ */
+class LogSystem :
+    private Noncopyable
+{
+  private:
+    typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
+    AbstractLogProviderPtrList m_providers;
+
+    bool m_isLoggingEnabled;
+
+  public:
+    bool IsLoggingEnabled() const;
+    LogSystem();
+    virtual ~LogSystem();
+
+    /**
+     * Log debug message
+     */
+    void Debug(const char *message,
+               const char *filename,
+               int line,
+               const char *function);
+
+    /**
+     * Log info message
+     */
+    void Info(const char *message,
+              const char *filename,
+              int line,
+              const char *function);
+
+    /**
+     * Log warning message
+     */
+    void Warning(const char *message,
+                 const char *filename,
+                 int line,
+                 const char *function);
+
+    /**
+     * Log error message
+     */
+    void Error(const char *message,
+               const char *filename,
+               int line,
+               const char *function);
+
+    /**
+     * Log pedantic message
+     */
+    void Pedantic(const char *message,
+                  const char *filename,
+                  int line,
+                  const char *function);
+
+    /**
+     * Log pedantic message with secure macro
+     */
+    void SecureDebug(const char *message,
+               const char *filename,
+               int line,
+               const char *function);
+
+    /**
+     * Log info message with secure macro
+     */
+    void SecureInfo(const char *message,
+              const char *filename,
+              int line,
+              const char *function);
+
+    /**
+     * Log warning message with secure macro
+     */
+    void SecureWarning(const char *message,
+                 const char *filename,
+                 int line,
+                 const char *function);
+
+    /**
+     * Log error message with secure macro
+     */
+    void SecureError(const char *message,
+               const char *filename,
+               int line,
+               const char *function);
+
+    /**
+     * Log SS_SMACK into files
+     */
+     void SmackAudit(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+
+    /**
+     * Set default's DLOG provider Tag
+     */
+    void SetTag(const char *tag);
+
+    /**
+     * Add abstract provider to providers list
+     *
+     * @notice Ownership is transfered to LogSystem and deleted upon exit
+     */
+    void AddProvider(AbstractLogProvider *provider);
+
+    /**
+     * Remove abstract provider from providers list
+     */
+    void RemoveProvider(AbstractLogProvider *provider);
+};
+
+/*
+ * Replacement low overhead null logging class
+ */
+class NullStream
+{
+  public:
+    NullStream() {}
+
+    template <typename T>
+    NullStream& operator<<(const T&)
+    {
+        return *this;
+    }
+};
+
+/**
+ * Log system singleton
+ */
+typedef Singleton<LogSystem> LogSystemSingleton;
+}
+} // namespace SecurityServer
+
+//
+// Log support
+//
+//
+
+/* avoid warnings about unused variables */
+#define DPL_MACRO_DUMMY_LOGGING(message, function)                         \
+    do {                                                                   \
+        SecurityServer::Log::NullStream ns;                                \
+        ns << message;                                                     \
+    } while (0)
+
+#define DPL_MACRO_FOR_LOGGING(message, function)                           \
+do                                                                         \
+{                                                                          \
+    if (SecurityServer::Log::LogSystemSingleton::Instance().IsLoggingEnabled())   \
+    {                                                                      \
+        std::ostringstream platformLog;                                    \
+        platformLog << message;                                            \
+        SecurityServer::Log::LogSystemSingleton::Instance().function(      \
+            platformLog.str().c_str(),                                     \
+            __FILE__, __LINE__, __FUNCTION__);                             \
+    }                                                                      \
+} while (0)
+
+/* Errors must be always logged. */
+#define  LogError(message) DPL_MACRO_FOR_LOGGING(message, Error)
+#define  LogSecureError(message) DPL_MACRO_FOR_LOGGING(message, SecureError)
+
+#define  LogSmackAudit(message) DPL_MACRO_FOR_LOGGING(message, SmackAudit)
+
+#ifdef BUILD_TYPE_DEBUG
+    #define LogDebug(message) DPL_MACRO_FOR_LOGGING(message, Debug)
+    #define LogInfo(message) DPL_MACRO_FOR_LOGGING(message, Info)
+    #define LogWarning(message) DPL_MACRO_FOR_LOGGING(message, Warning)
+    #define LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, Pedantic)
+    #define LogSecureDebug(message) DPL_MACRO_FOR_LOGGING(message, SecureDebug)
+    #define LogSecureInfo(message) DPL_MACRO_FOR_LOGGING(message, SecureInfo)
+    #define LogSecureWarning(message) DPL_MACRO_FOR_LOGGING(message, SecureWarning)
+#else
+    #define LogDebug(message) DPL_MACRO_DUMMY_LOGGING(message, Debug)
+    #define LogInfo(message) DPL_MACRO_DUMMY_LOGGING(message, Info)
+    #define LogWarning(message) DPL_MACRO_DUMMY_LOGGING(message, Warning)
+    #define LogPedantic(message) DPL_MACRO_DUMMY_LOGGING(message, Pedantic)
+    #define LogSecureDebug(message) DPL_MACRO_DUMMY_LOGGING(message, SecureDebug)
+    #define LogSecureInfo(message) DPL_MACRO_DUMMY_LOGGING(message, SecureInfo)
+    #define LogSecureWarning(message) DPL_MACRO_DUMMY_LOGGING(message, SecureWarning)
+#endif // BUILD_TYPE_DEBUG
+
+#endif // SECURITYSERVER_LOG_H
diff --git a/src/server/dpl/log/include/dpl/log/old_style_log_provider.h b/src/server/dpl/log/include/dpl/log/old_style_log_provider.h
new file mode 100644 (file)
index 0000000..91eeb80
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2011 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        old_style_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of old style log provider
+ */
+#ifndef SECURITYSERVER_OLD_STYLE_LOG_PROVIDER_H
+#define SECURITYSERVER_OLD_STYLE_LOG_PROVIDER_H
+
+#include <dpl/log/abstract_log_provider.h>
+#include <string>
+
+namespace SecurityServer {
+namespace Log {
+class OldStyleLogProvider :
+    public AbstractLogProvider
+{
+  private:
+    bool m_showDebug;
+    bool m_showInfo;
+    bool m_showWarning;
+    bool m_showError;
+    bool m_showPedantic;
+    bool m_printStdErr;
+
+    static std::string FormatMessage(const char *message,
+                                     const char *filename,
+                                     int line,
+                                     const char *function);
+
+  public:
+    OldStyleLogProvider(bool showDebug,
+                        bool showInfo,
+                        bool showWarning,
+                        bool showError,
+                        bool showPedantic);
+    OldStyleLogProvider(bool showDebug,
+                        bool showInfo,
+                        bool showWarning,
+                        bool showError,
+                        bool showPedantic,
+                        bool printStdErr);
+    virtual ~OldStyleLogProvider() {}
+
+    virtual void Debug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Info(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+    virtual void Warning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function);
+    virtual void Error(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Pedantic(const char *message,
+                          const char *fileName,
+                          int line,
+                          const char *function);
+    virtual void SecureDebug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void SecureInfo(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+    virtual void SecureWarning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function);
+    virtual void SecureError(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void SmackAudit(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+};
+}
+} // namespace SecurityServer
+
+#endif // SECURITYSERVER_OLD_STYLE_LOG_PROVIDER_H
diff --git a/src/server/dpl/log/src/abstract_log_provider.cpp b/src/server/dpl/log/src/abstract_log_provider.cpp
new file mode 100644 (file)
index 0000000..1da7bba
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2011 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        abstract_log_provider.cpp
+ * @author      Pawel Sikorski (p.sikorski@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of abstract log provider
+ */
+#include <stddef.h>
+#include <dpl/log/abstract_log_provider.h>
+#include <cstring>
+
+#define UNUSED __attribute__((unused))
+
+namespace SecurityServer {
+namespace Log {
+
+void AbstractLogProvider::SetTag(const char *tag UNUSED) {}
+
+const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
+{
+    const char *ptr = strrchr(filename, '/');
+    return ptr != NULL ? ptr + 1 : filename;
+}
+}
+}
diff --git a/src/server/dpl/log/src/audit-smack-log.cpp b/src/server/dpl/log/src/audit-smack-log.cpp
new file mode 100644 (file)
index 0000000..c442955
--- /dev/null
@@ -0,0 +1,308 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        audit-smack-log.cpp
+ * @author      Marek Smolinski (m.smolinski@samsung.com)
+ * @version     1.0
+ * @brief       AuditSmackLog loging SMACK access deny sequentially into files
+ */
+
+#include <iostream>
+#include <fstream>
+#include <map>
+#include <cstring>
+#include <mutex>
+
+#include <dirent.h>
+#include <time.h>
+#include <errno.h>
+#include <unistd.h>
+#include <cassert>
+
+#include <sys/smack.h>
+#include <sys/stat.h>
+
+#include <dpl/log/audit-smack-log.h>
+#include <dpl/log/log.h>
+
+#define UNUSED __attribute__((unused))
+
+namespace {
+
+const std::string AUDIT_CONFIG_LOG_PATH = "/etc/security/";
+const std::string AUDIT_CONFIG_FILENAME = "security-server-audit.conf";
+const std::string AUDIT_LOG_DIRECTORY = "/var/log/audit/";
+const std::string AUDIT_LOG_FILENAME_PREFIX = "audit-smack";
+const std::string AUDIT_LOG_SMACK_LABEL = "security-server::audit-files";
+
+} // namespace anonymous
+
+namespace SecurityServer {
+namespace Log {
+
+AuditSmackLog::AuditSmackLog()
+    : m_state(true), m_filesCount(0), m_fileMaxBytesSize(0)
+{
+    if (ParseConfig() != 0) {
+        goto error;
+    }
+
+    if (ProcessLogDir() != 0) {
+        goto error;
+    }
+
+    if (m_state) {
+
+        // reduce existing files count in log dir if config file was changed
+        while (m_fileNameMap.size() > m_filesCount) {
+            if (RemoveOldestLogFile() != 0) {
+                goto error;
+            }
+        }
+
+        if (m_fileNameMap.size() == 0) {
+            if (CreateLogFile() != 0) {
+                goto error;
+            }
+        } else {
+            std::string filename(AUDIT_LOG_DIRECTORY);
+            filename += m_fileNameMap.rbegin()->second;
+            m_outputStream.open(filename, std::ios_base::app);
+        }
+    }
+
+    return;
+
+error:
+    m_state = false;
+
+}
+
+AuditSmackLog::~AuditSmackLog(){}
+
+bool AuditSmackLog::Fail() const
+{
+    return !m_state;
+}
+
+void AuditSmackLog::SmackAudit(const char *message,
+                               const char *fileName,
+                               int line,
+                               const char *function)
+{
+    if (m_state) {
+        HandleWrite(message, fileName, line, function);
+    }
+}
+
+void AuditSmackLog::HandleWrite(const char *message,
+                                const char *filename,
+                                int line,
+                                const char *function)
+{
+    std::lock_guard<std::mutex> lock(m_writeMtx);
+    if (IsFileFull(m_outputStream)) {
+        if (CreateLogFile() != 0) {
+            m_state = false;
+            return;
+        }
+
+        if (m_fileNameMap.size() > m_filesCount) {
+            if (RemoveOldestLogFile() != 0) {
+                m_state = false;
+                return;
+            }
+        }
+    }
+
+    m_outputStream << std::string("[") <<
+        LocateSourceFileName(filename) << std::string(":") << line <<
+        std::string("] ") << function << std::string("(): ") << message << '\n';
+}
+
+int AuditSmackLog::CreateLogFile()
+{
+    time_t sec = time(NULL);
+    std::string fname(AUDIT_LOG_FILENAME_PREFIX);
+    std::string pathname(AUDIT_LOG_DIRECTORY);
+
+    fname += std::to_string(sec);
+    fname += ".log";
+    pathname += fname;
+
+    if (m_outputStream.is_open())
+        m_outputStream.close();
+
+    m_outputStream.open(pathname.c_str());
+
+    if (!m_outputStream) {
+        return -1;
+    }
+
+    if (smack_setlabel(pathname.c_str(),
+                       AUDIT_LOG_SMACK_LABEL.c_str(),
+                       SMACK_LABEL_ACCESS) != 0)  {
+        return -1;
+    }
+
+    m_fileNameMap.insert(std::make_pair(sec, fname));
+    return 0;
+}
+
+int AuditSmackLog::RemoveOldestLogFile()
+{
+    assert(m_fileNameMap.size() > 0);
+
+    auto it = m_fileNameMap.begin();
+    std::string filename(AUDIT_LOG_DIRECTORY);
+    filename += it->second;
+
+    if (unlink(filename.c_str()) == 0) {
+        m_fileNameMap.erase(it);
+        return 0;
+    }
+
+    return -1;
+}
+
+int AuditSmackLog::ParseConfig()
+{
+    struct stat sb;
+    if (stat(AUDIT_CONFIG_LOG_PATH.c_str(), &sb) != 0) {
+        return -1;
+    }
+
+    std::ifstream in(AUDIT_CONFIG_LOG_PATH + AUDIT_CONFIG_FILENAME,
+                     std::ios_base::in);
+    if (!in) {
+        return -1;
+    }
+
+    in >> m_filesCount >> m_fileMaxBytesSize;
+
+    if (in.fail()) {
+        return -1;
+    }
+
+    return (m_filesCount > 0 && m_fileMaxBytesSize > 0) ? 0 : -1;
+}
+
+int AuditSmackLog::ProcessLogDir()
+{
+    DIR *dir;
+    dirent *dp;
+
+    if ((dir = opendir(AUDIT_LOG_DIRECTORY.c_str())) == NULL) {
+        return -1;
+    }
+
+    while ((dp = readdir(dir)) != NULL) {
+        if (AUDIT_LOG_FILENAME_PREFIX.compare(0, std::string::npos,
+                                      dp->d_name,
+                                      AUDIT_LOG_FILENAME_PREFIX.size()) == 0) {
+            errno = 0;
+            char *pEnd;
+            time_t fUnxTime = static_cast<time_t>(
+                    strtoull(dp->d_name + AUDIT_LOG_FILENAME_PREFIX.size(),
+                             &pEnd, 10));
+
+            if (errno != 0) {
+                closedir(dir);
+                return -1;
+            }
+
+            m_fileNameMap.insert(
+                    std::make_pair(fUnxTime, std::string(dp->d_name)));
+        }
+    }
+
+    closedir(dir);
+
+    return 0;
+}
+
+bool AuditSmackLog::IsFileFull(std::ofstream &fs) const
+{
+    return fs.tellp() > m_fileMaxBytesSize;
+}
+
+void AuditSmackLog::Debug(const char *message UNUSED,
+                          const char *filename UNUSED,
+                          int line UNUSED,
+                          const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::Info(const char *message UNUSED,
+                         const char *filename UNUSED,
+                         int line UNUSED,
+                         const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::Warning(const char *message UNUSED,
+                            const char *filename UNUSED,
+                            int line UNUSED,
+                            const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::Error(const char *message UNUSED,
+                          const char *filename UNUSED,
+                          int line UNUSED,
+                          const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::Pedantic(const char *message UNUSED,
+                             const char *filename UNUSED,
+                             int line UNUSED,
+                             const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::SecureDebug(const char *message UNUSED,
+                                const char *filename UNUSED,
+                                int line UNUSED,
+                                const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::SecureInfo(const char *message UNUSED,
+                               const char *filename  UNUSED,
+                               int line  UNUSED,
+                               const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::SecureWarning(const char *message UNUSED,
+                                  const char *filename UNUSED,
+                                  int line UNUSED,
+                                  const char *function UNUSED)
+{
+}
+
+void AuditSmackLog::SecureError(const char *message UNUSED,
+                                const char *filename UNUSED,
+                                int line UNUSED,
+                                const char *function UNUSED)
+{
+}
+
+} // namespace Log
+} // namespace SecurityServer
diff --git a/src/server/dpl/log/src/dlog_log_provider.cpp b/src/server/dpl/log/src/dlog_log_provider.cpp
new file mode 100644 (file)
index 0000000..90f0713
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2011 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_log_provider.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of DLOG log provider
+ */
+#include <stddef.h>
+#include <dpl/log/dlog_log_provider.h>
+#include <cstring>
+#include <sstream>
+#include <dlog.h>
+
+#define UNUSED __attribute__((unused))
+
+namespace SecurityServer {
+namespace Log {
+std::string DLOGLogProvider::FormatMessage(const char *message,
+                                           const char *filename,
+                                           int line,
+                                           const char *function)
+{
+    std::ostringstream val;
+
+    val << std::string("[") <<
+    LocateSourceFileName(filename) << std::string(":") << line <<
+    std::string("] ") << function << std::string("(): ") << message;
+
+    return val.str();
+}
+
+DLOGLogProvider::DLOGLogProvider()
+{}
+
+DLOGLogProvider::~DLOGLogProvider()
+{}
+
+void DLOGLogProvider::SetTag(const char *tag)
+{
+    size_t size = strlen(tag)+1;
+    char *buff = new (std::nothrow) char[size];
+    if (buff)
+        memcpy(buff, tag, size);
+    m_tag.reset(buff);
+}
+
+void DLOGLogProvider::Debug(const char *message,
+                            const char *filename,
+                            int line,
+                            const char *function)
+{
+    SLOG(LOG_DEBUG, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Info(const char *message,
+                           const char *filename,
+                           int line,
+                           const char *function)
+{
+    SLOG(LOG_INFO, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Warning(const char *message,
+                              const char *filename,
+                              int line,
+                              const char *function)
+{
+    SLOG(LOG_WARN, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Error(const char *message,
+                            const char *filename,
+                            int line,
+                            const char *function)
+{
+    SLOG(LOG_ERROR, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Pedantic(const char *message,
+                               const char *filename,
+                               int line,
+                               const char *function)
+{
+    SLOG(LOG_DEBUG, "SecurityServer", "%s", FormatMessage(message,
+                                              filename,
+                                              line,
+                                              function).c_str());
+}
+
+void DLOGLogProvider::SecureDebug(const char *message UNUSED,
+                            const char *filename UNUSED,
+                            int line UNUSED,
+                            const char *function UNUSED)
+{
+    SECURE_SLOG(LOG_DEBUG, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::SecureInfo(const char *message UNUSED,
+                           const char *filename UNUSED,
+                           int line UNUSED,
+                           const char *function UNUSED)
+{
+    SECURE_SLOG(LOG_INFO, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::SecureWarning(const char *message UNUSED,
+                              const char *filename UNUSED,
+                              int line UNUSED,
+                              const char *function UNUSED)
+{
+    SECURE_SLOG(LOG_WARN, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::SecureError(const char *message UNUSED,
+                            const char *filename UNUSED,
+                            int line UNUSED,
+                            const char *function UNUSED)
+{
+    SECURE_SLOG(LOG_ERROR, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::SmackAudit(const char *message UNUSED,
+                           const char *filename UNUSED,
+                           int line UNUSED,
+                           const char *function UNUSED)
+{
+}
+
+} // nemespace Log
+} // namespace SecurityServer
diff --git a/src/server/dpl/log/src/log.cpp b/src/server/dpl/log/src/log.cpp
new file mode 100644 (file)
index 0000000..a91cdb2
--- /dev/null
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) 2011 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.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of log system
+ */
+#include <stddef.h>
+#include <string.h>
+
+#include <dpl/log/log.h>
+#include <dpl/singleton_impl.h>
+#include <dpl/log/dlog_log_provider.h>
+#include <dpl/log/old_style_log_provider.h>
+#include <dpl/log/audit-smack-log.h>
+
+IMPLEMENT_SINGLETON(SecurityServer::Log::LogSystem)
+
+namespace SecurityServer {
+namespace Log {
+namespace // anonymous
+{
+#ifdef BUILD_TYPE_DEBUG
+const char *OLD_STYLE_LOGS_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS";
+const char *OLD_STYLE_PEDANTIC_LOGS_ENV_NAME =
+    "DPL_USE_OLD_STYLE_PEDANTIC_LOGS";
+const char *OLD_STYLE_LOGS_MASK_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS_MASK";
+#endif // BUILD_TYPE_DEBUG
+const char *SECURITY_SERVER_LOG_OFF = "DPL_LOG_OFF";
+} // namespace anonymous
+
+bool LogSystem::IsLoggingEnabled() const
+{
+    return m_isLoggingEnabled;
+}
+
+LogSystem::LogSystem() :
+    m_isLoggingEnabled(!getenv(SECURITY_SERVER_LOG_OFF))
+{
+#ifdef BUILD_TYPE_DEBUG
+    bool oldStyleLogs = false;
+    bool oldStyleDebugLogs = true;
+    bool oldStyleInfoLogs = true;
+    bool oldStyleWarningLogs = true;
+    bool oldStyleErrorLogs = true;
+    bool oldStylePedanticLogs = false;
+
+    // Check environment settings about pedantic logs
+    const char *value = getenv(OLD_STYLE_LOGS_ENV_NAME);
+
+    if (value != NULL && !strcmp(value, "1")) {
+        oldStyleLogs = true;
+    }
+
+    value = getenv(OLD_STYLE_PEDANTIC_LOGS_ENV_NAME);
+
+    if (value != NULL && !strcmp(value, "1")) {
+        oldStylePedanticLogs = true;
+    }
+
+    value = getenv(OLD_STYLE_LOGS_MASK_ENV_NAME);
+
+    if (value != NULL) {
+        size_t len = strlen(value);
+
+        if (len >= 1) {
+            if (value[0] == '0') {
+                oldStyleDebugLogs = false;
+            } else if (value[0] == '1') {
+                oldStyleDebugLogs = true;
+            }
+        }
+
+        if (len >= 2) {
+            if (value[1] == '0') {
+                oldStyleInfoLogs = false;
+            } else if (value[1] == '1') {
+                oldStyleInfoLogs = true;
+            }
+        }
+
+        if (len >= 3) {
+            if (value[2] == '0') {
+                oldStyleWarningLogs = false;
+            } else if (value[2] == '1') {
+                oldStyleWarningLogs = true;
+            }
+        }
+
+        if (len >= 4) {
+            if (value[3] == '0') {
+                oldStyleErrorLogs = false;
+            } else if (value[3] == '1') {
+                oldStyleErrorLogs = true;
+            }
+        }
+    }
+
+    // Setup default DLOG and old style logging
+    if (oldStyleLogs) {
+        // Old style
+        AddProvider(new OldStyleLogProvider(oldStyleDebugLogs,
+                                            oldStyleInfoLogs,
+                                            oldStyleWarningLogs,
+                                            oldStyleErrorLogs,
+                                            oldStylePedanticLogs));
+    } else {
+        // DLOG
+        AddProvider(new DLOGLogProvider());
+    }
+#else // BUILD_TYPE_DEBUG
+    AddProvider(new DLOGLogProvider());
+#endif // BUILD_TYPE_DEBUG
+
+    AuditSmackLog * smackLog = new AuditSmackLog();
+    if (smackLog->Fail()) {
+        delete smackLog;
+    } else {
+        AddProvider(smackLog);
+    }
+}
+
+LogSystem::~LogSystem()
+{
+    // Delete all providers
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        delete *iterator;
+    }
+
+    m_providers.clear();
+}
+
+void LogSystem::SetTag(const char* tag)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->SetTag(tag);
+    }
+}
+
+void LogSystem::AddProvider(AbstractLogProvider *provider)
+{
+    m_providers.push_back(provider);
+}
+
+void LogSystem::RemoveProvider(AbstractLogProvider *provider)
+{
+    m_providers.remove(provider);
+}
+
+void LogSystem::Debug(const char *message,
+                      const char *filename,
+                      int line,
+                      const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Debug(message, filename, line, function);
+    }
+}
+
+void LogSystem::Info(const char *message,
+                     const char *filename,
+                     int line,
+                     const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Info(message, filename, line, function);
+    }
+}
+
+void LogSystem::Warning(const char *message,
+                        const char *filename,
+                        int line,
+                        const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Warning(message, filename, line, function);
+    }
+}
+
+void LogSystem::Error(const char *message,
+                      const char *filename,
+                      int line,
+                      const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Error(message, filename, line, function);
+    }
+}
+
+void LogSystem::Pedantic(const char *message,
+                         const char *filename,
+                         int line,
+                         const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Pedantic(message, filename, line, function);
+    }
+}
+
+void LogSystem::SecureInfo(const char *message,
+                         const char *filename,
+                         int line,
+                         const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->SecureInfo(message, filename, line, function);
+    }
+}
+
+void LogSystem::SecureDebug(const char *message,
+                         const char *filename,
+                         int line,
+                         const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->SecureDebug(message, filename, line, function);
+    }
+}
+
+void LogSystem::SecureError(const char *message,
+                         const char *filename,
+                         int line,
+                         const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->SecureError(message, filename, line, function);
+    }
+}
+
+void LogSystem::SecureWarning(const char *message,
+                         const char *filename,
+                         int line,
+                         const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->SecureWarning(message, filename, line, function);
+    }
+}
+
+void LogSystem::SmackAudit(const char *message,
+                     const char *fileName,
+                     int line,
+                     const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->SmackAudit(message, fileName, line, function);
+    }
+}
+
+}
+} // namespace SecurityServer
diff --git a/src/server/dpl/log/src/old_style_log_provider.cpp b/src/server/dpl/log/src/old_style_log_provider.cpp
new file mode 100644 (file)
index 0000000..4c10749
--- /dev/null
@@ -0,0 +1,313 @@
+/*
+ * Copyright (c) 2011 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        old_style_log_provider.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of old style log provider
+ */
+#include <stddef.h>
+#include <dpl/log/old_style_log_provider.h>
+#include <dpl/colors.h>
+#include <cstdio>
+#include <cstring>
+#include <sstream>
+#include <sys/time.h>
+#include <unistd.h>
+#include <dlog.h>
+
+namespace SecurityServer {
+namespace Log {
+namespace // anonymous
+{
+using namespace SecurityServer::Colors::Text;
+const char *DEBUG_BEGIN = GREEN_BEGIN;
+const char *DEBUG_END = GREEN_END;
+const char *INFO_BEGIN = CYAN_BEGIN;
+const char *INFO_END = CYAN_END;
+const char *ERROR_BEGIN = RED_BEGIN;
+const char *ERROR_END = RED_END;
+const char *WARNING_BEGIN = BOLD_GOLD_BEGIN;
+const char *WARNING_END = BOLD_GOLD_END;
+const char *PEDANTIC_BEGIN = PURPLE_BEGIN;
+const char *PEDANTIC_END = PURPLE_END;
+
+std::string GetFormattedTime()
+{
+    timeval tv;
+    tm localNowTime;
+
+    gettimeofday(&tv, NULL);
+    localtime_r(&tv.tv_sec, &localNowTime);
+
+    char format[64];
+    snprintf(format,
+             sizeof(format),
+             "%02i:%02i:%02i.%03i",
+             localNowTime.tm_hour,
+             localNowTime.tm_min,
+             localNowTime.tm_sec,
+             static_cast<int>(tv.tv_usec / 1000));
+    return format;
+}
+} // namespace anonymous
+
+std::string OldStyleLogProvider::FormatMessage(const char *message,
+                                               const char *filename,
+                                               int line,
+                                               const char *function)
+{
+    std::ostringstream val;
+
+    val << std::string("[") << GetFormattedTime() << std::string("] [") <<
+    static_cast<unsigned long>(pthread_self()) << "/" <<
+    static_cast<int>(getpid()) << std::string("] [") <<
+    LocateSourceFileName(filename) << std::string(":") << line <<
+    std::string("] ") << function << std::string("(): ") << message;
+
+    return val.str();
+}
+
+OldStyleLogProvider::OldStyleLogProvider(bool showDebug,
+                                         bool showInfo,
+                                         bool showWarning,
+                                         bool showError,
+                                         bool showPedantic) :
+    m_showDebug(showDebug),
+    m_showInfo(showInfo),
+    m_showWarning(showWarning),
+    m_showError(showError),
+    m_showPedantic(showPedantic),
+    m_printStdErr(false)
+{}
+
+OldStyleLogProvider::OldStyleLogProvider(bool showDebug,
+                                         bool showInfo,
+                                         bool showWarning,
+                                         bool showError,
+                                         bool showPedantic,
+                                         bool printStdErr) :
+    m_showDebug(showDebug),
+    m_showInfo(showInfo),
+    m_showWarning(showWarning),
+    m_showError(showError),
+    m_showPedantic(showPedantic),
+    m_printStdErr(printStdErr)
+{}
+
+void OldStyleLogProvider::Debug(const char *message,
+                                const char *filename,
+                                int line,
+                                const char *function)
+{
+    if (m_showDebug) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), DEBUG_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), DEBUG_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Info(const char *message,
+                               const char *filename,
+                               int line,
+                               const char *function)
+{
+    if (m_showInfo) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), INFO_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), INFO_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Warning(const char *message,
+                                  const char *filename,
+                                  int line,
+                                  const char *function)
+{
+    if (m_showWarning) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), WARNING_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), WARNING_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Error(const char *message,
+                                const char *filename,
+                                int line,
+                                const char *function)
+{
+    if (m_showError) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), ERROR_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), ERROR_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Pedantic(const char *message,
+                                   const char *filename,
+                                   int line,
+                                   const char *function)
+{
+    if (m_showPedantic) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", PEDANTIC_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), PEDANTIC_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", PEDANTIC_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), PEDANTIC_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::SecureDebug(const char *message,
+                                const char *filename,
+                                int line,
+                                const char *function)
+{
+#ifdef _SECURE_LOG
+    if (m_showDebug) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), DEBUG_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), DEBUG_END);
+        }
+    }
+#else
+    (void)message;
+    (void)filename;
+    (void)line;
+    (void)function;
+#endif
+}
+
+void OldStyleLogProvider::SecureInfo(const char *message,
+                               const char *filename,
+                               int line,
+                               const char *function)
+{
+#ifdef _SECURE_LOG
+    if (m_showInfo) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), INFO_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), INFO_END);
+        }
+    }
+#else
+    (void)message;
+    (void)filename;
+    (void)line;
+    (void)function;
+#endif
+}
+
+void OldStyleLogProvider::SecureWarning(const char *message,
+                                  const char *filename,
+                                  int line,
+                                  const char *function)
+{
+#ifdef _SECURE_LOG
+    if (m_showWarning) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), WARNING_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), WARNING_END);
+        }
+    }
+#else
+    (void)message;
+    (void)filename;
+    (void)line;
+    (void)function;
+#endif
+}
+
+void OldStyleLogProvider::SecureError(const char *message,
+                                const char *filename,
+                                int line,
+                                const char *function)
+{
+#ifdef _SECURE_LOG
+    if (m_showError) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), ERROR_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), ERROR_END);
+        }
+    }
+#else
+    (void)message;
+    (void)filename;
+    (void)line;
+    (void)function;
+#endif
+}
+
+void OldStyleLogProvider::SmackAudit(const char *message,
+                               const char *fileName,
+                               int line,
+                               const char *function)
+{
+    (void)message;
+    (void)fileName;
+    (void)line;
+    (void)function;
+}
+
+}
+} // namespace SecurityServer
diff --git a/src/server/main/generic-event.h b/src/server/main/generic-event.h
new file mode 100644 (file)
index 0000000..30d9e88
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        protocols.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of GenericEvent.
+ */
+
+#ifndef _SECURITY_SERVER_GENERIC_EVENT_
+#define _SECURITY_SERVER_GENERIC_EVENT_
+
+namespace SecurityServer {
+
+struct GenericEvent {
+    virtual ~GenericEvent(){}
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_GENERIC_EVENT_
diff --git a/src/server/main/generic-socket-manager.cpp b/src/server/main/generic-socket-manager.cpp
new file mode 100644 (file)
index 0000000..5bf0695
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        generic-socket-manager.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of GenericSocketService and GenericSocketManager.
+ */
+
+#include <sys/socket.h>
+#include <sys/types.h>
+
+#include <generic-socket-manager.h>
+
+namespace SecurityServer {
+
+class SendMsgData::Internal {
+public:
+    Internal(int resultCode, int fileDesc)
+      : m_resultCode(resultCode)
+      , m_fileDesc(fileDesc)
+    {
+        memset(&m_hdr, 0, sizeof(msghdr));
+        memset(m_cmsgbuf, 0, CMSG_SPACE(sizeof(int)));
+
+        m_iov.iov_base = &m_resultCode;
+        m_iov.iov_len = sizeof(m_resultCode);
+
+        m_hdr.msg_iov = &m_iov;
+        m_hdr.msg_iovlen = 1;
+
+        if (fileDesc != -1) {
+            m_hdr.msg_control = m_cmsgbuf;
+            m_hdr.msg_controllen = CMSG_SPACE(sizeof(int));
+
+            m_cmsg = CMSG_FIRSTHDR(&m_hdr);
+            m_cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+            m_cmsg->cmsg_level = SOL_SOCKET;
+            m_cmsg->cmsg_type = SCM_RIGHTS;
+
+            memmove(CMSG_DATA(m_cmsg), &m_fileDesc, sizeof(int));
+        }
+    }
+
+    msghdr* data() { return &m_hdr; }
+
+private:
+    msghdr m_hdr;
+    iovec m_iov;
+    cmsghdr *m_cmsg;
+    unsigned char m_cmsgbuf[CMSG_SPACE(sizeof(int))];
+    int m_resultCode;
+    int m_fileDesc;
+};
+
+SendMsgData::SendMsgData()
+  : m_resultCode(0)
+  , m_fileDesc(-1)
+  , m_flags(0)
+  , m_pimpl(NULL)
+{}
+
+SendMsgData::SendMsgData(int resultCode, int fileDesc, int flags)
+  : m_resultCode(resultCode)
+  , m_fileDesc(fileDesc)
+  , m_flags(flags)
+  , m_pimpl(NULL)
+{}
+
+SendMsgData::SendMsgData(const SendMsgData &second)
+  : m_resultCode(second.m_resultCode)
+  , m_fileDesc(second.m_fileDesc)
+  , m_flags(second.m_flags)
+  , m_pimpl(NULL)
+{}
+
+SendMsgData::~SendMsgData() {
+    delete m_pimpl;
+}
+
+SendMsgData& SendMsgData::operator=(const SendMsgData &second) {
+    m_resultCode = second.m_resultCode;
+    m_fileDesc = second.m_fileDesc;
+    m_flags = second.m_flags;
+    delete m_pimpl;
+    m_pimpl = NULL;
+    return *this;
+}
+
+msghdr* SendMsgData::getMsghdr() {
+    if (!m_pimpl)
+        m_pimpl = new Internal(m_resultCode, m_fileDesc);
+    return m_pimpl->data();
+}
+
+int SendMsgData::flags() {
+    return m_flags;
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/main/generic-socket-manager.h b/src/server/main/generic-socket-manager.h
new file mode 100644 (file)
index 0000000..4417a30
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        generic-socket-manager.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of GenericSocketService and GenericSocketManager.
+ */
+
+#ifndef _SECURITY_SERVER_GENERIC_SERVICE_MANAGER_
+#define _SECURITY_SERVER_GENERIC_SERVICE_MANAGER_
+
+#include <vector>
+#include <string>
+
+#include <dpl/exception.h>
+
+#include <generic-event.h>
+
+extern "C" {
+struct msghdr;
+} // extern "C"
+
+namespace SecurityServer {
+
+typedef int InterfaceID;
+
+struct ConnectionID {
+    int sock;                                 // This is decriptor used for connection
+    int counter;                              // Unique handler per socket
+    inline bool operator<(const ConnectionID &second) const {
+        return counter < second.counter;
+    }
+};
+
+typedef std::vector<unsigned char> RawBuffer;
+
+struct GenericSocketManager;
+
+struct GenericSocketService {
+    typedef std::string SmackLabel;
+    typedef std::string ServiceHandlerPath;
+    struct ServiceDescription {
+        ServiceDescription(const char *path,
+            const char *smackLabel,
+            InterfaceID interfaceID = 0,
+            bool useSendMsg = false)
+          : smackLabel(smackLabel)
+          , interfaceID(interfaceID)
+          , serviceHandlerPath(path)
+          , useSendMsg(useSendMsg)
+        {}
+
+        SmackLabel smackLabel;                 // Smack label for socket
+        InterfaceID interfaceID;               // All data from serviceHandlerPath will be marked with this interfaceHandler
+        ServiceHandlerPath serviceHandlerPath; // Path to file
+        bool useSendMsg;
+    };
+
+    typedef std::vector<ServiceDescription> ServiceDescriptionVector;
+
+    struct AcceptEvent : public GenericEvent {
+        ConnectionID connectionID;
+        InterfaceID interfaceID;
+    };
+
+    struct WriteEvent : public GenericEvent {
+        ConnectionID connectionID;
+        size_t size;
+        size_t left;
+    };
+
+    struct ReadEvent : public GenericEvent {
+        ConnectionID connectionID;
+        RawBuffer rawBuffer;
+    };
+
+    struct CloseEvent : public GenericEvent {
+        ConnectionID connectionID;
+    };
+
+    virtual void SetSocketManager(GenericSocketManager *manager) {
+        m_serviceManager = manager;
+    }
+
+    virtual ServiceDescriptionVector GetServiceDescription() = 0;
+    virtual void Event(const AcceptEvent &event) = 0;
+    virtual void Event(const WriteEvent &event) = 0;
+    virtual void Event(const ReadEvent &event) = 0;
+    virtual void Event(const CloseEvent &event) = 0;
+
+    GenericSocketService() : m_serviceManager(NULL) {}
+    virtual ~GenericSocketService(){}
+protected:
+    GenericSocketManager *m_serviceManager;
+};
+
+class SendMsgData {
+public:
+    class Internal;
+
+    SendMsgData();
+    SendMsgData(int resultCode, int fileDesc, int flags = 0);
+    SendMsgData(const SendMsgData &second);
+    SendMsgData& operator=(const SendMsgData &second);
+    virtual ~SendMsgData();
+
+    msghdr* getMsghdr();
+    int flags();
+private:
+    int m_resultCode;
+    int m_fileDesc;
+    int m_flags;
+    Internal *m_pimpl;
+};
+
+struct GenericSocketManager {
+    virtual void MainLoop() = 0;
+    virtual void RegisterSocketService(GenericSocketService *ptr) = 0;
+    virtual void Close(ConnectionID connectionID) = 0;
+    virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer) = 0;
+    virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData) = 0;
+    virtual ~GenericSocketManager(){}
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_GENERIC_SERVICE_MANAGER_
diff --git a/src/server/main/security-server-util.cpp b/src/server/main/security-server-util.cpp
new file mode 100644 (file)
index 0000000..2641376
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/smack.h>
+#include <unistd.h>
+
+#include <limits>
+
+#include <security-server-util.h>
+#include <dpl/log/log.h>
+
+namespace {
+const size_t SIZE_T_MAX = std::numeric_limits<size_t>::max();
+} // namespace anonymous
+
+namespace SecurityServer {
+
+int util_smack_label_is_valid(const char *smack_label)
+{
+    int i;
+
+    if (!smack_label || smack_label[0] == '\0' || smack_label[0] == '-')
+        goto err;
+
+    for (i = 0; smack_label[i]; ++i) {
+        if (i >= SMACK_LABEL_LEN)
+            return 0;
+        switch (smack_label[i]) {
+            case '~':
+            case ' ':
+            case '/':
+            case '"':
+            case '\\':
+            case '\'':
+                goto err;
+            default:
+                break;
+        }
+    }
+
+    return 1;
+err:
+    LogError("Invalid Smack label: " << smack_label);
+    return 0;
+}
+
+char *read_exe_path_from_proc(pid_t pid)
+{
+    char link[32];
+    char *exe = NULL;
+    size_t size = 64;
+    ssize_t cnt = 0;
+
+    // get link to executable
+    snprintf(link, sizeof(link), "/proc/%d/exe", pid);
+
+    for (;;)
+    {
+        exe = (char*) malloc(size);
+        if (exe == NULL)
+        {
+            LogError("Out of memory");
+            return NULL;
+        }
+
+        // read link target
+        cnt = readlink(link, exe, size);
+
+        // error
+        if (cnt < 0 || (size_t) cnt > size)
+        {
+            LogError("Can't locate process binary for pid=" << pid);
+            free(exe);
+            return NULL;
+        }
+
+        // read less than requested
+        if ((size_t) cnt < size)
+            break;
+
+        // read exactly the number of bytes requested
+        free(exe);
+        if (size > (SIZE_T_MAX >> 1))
+        {
+            LogError("Exe path too long (more than " << size << " characters)");
+            return NULL;
+        }
+        size <<= 1;
+    }
+    // readlink does not append null byte to buffer.
+    exe[cnt] = '\0';
+    return exe;
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/main/security-server-util.h b/src/server/main/security-server-util.h
new file mode 100644 (file)
index 0000000..3bb37d4
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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 SECURITY_SERVER_UTIL_H
+#define SECURITY_SERVER_UTIL_H
+
+#include <sys/types.h>
+
+namespace SecurityServer {
+
+int util_smack_label_is_valid(const char *smack_label);
+char *read_exe_path_from_proc(pid_t pid);
+
+} // namespace SecurityServer
+
+#endif /*SECURITY_SERVER_UTIL_H*/
diff --git a/src/server/main/server2-main.cpp b/src/server/main/server2-main.cpp
new file mode 100644 (file)
index 0000000..afc18a9
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        sever2-main.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of security-server2
+ */
+#include <stdlib.h>
+#include <signal.h>
+
+#include <dpl/log/log.h>
+#include <dpl/singleton.h>
+#include <dpl/singleton_safe_impl.h>
+
+#include <socket-manager.h>
+
+#include <data-share.h>
+#include <get-gid.h>
+#include <privilege-by-pid.h>
+#include <get-object-name.h>
+#include <app-permissions.h>
+#include <cookie.h>
+#include <open-for.h>
+#include <password.h>
+
+IMPLEMENT_SAFE_SINGLETON(SecurityServer::Log::LogSystem);
+
+int main(void) {
+
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        SecurityServer::Singleton<SecurityServer::Log::LogSystem>::Instance().SetTag("SECURITY_SERVER");
+
+        sigset_t mask;
+        sigemptyset(&mask);
+        sigaddset(&mask, SIGTERM);
+        sigaddset(&mask, SIGPIPE);
+        if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL)) {
+            LogError("Error in pthread_sigmask");
+            return 1;
+        }
+
+        LogInfo("Start!");
+        SecurityServer::SocketManager manager;
+
+        SecurityServer::OpenForService *openForService = new SecurityServer::OpenForService;
+        openForService->Create();
+        manager.RegisterSocketService(openForService);
+
+        SecurityServer::CookieService *cookieService = new SecurityServer::CookieService;
+        cookieService->Create();
+        manager.RegisterSocketService(cookieService);
+
+        SecurityServer::SharedMemoryService *shmService = new SecurityServer::SharedMemoryService;
+        shmService->Create();
+        manager.RegisterSocketService(shmService);
+
+        SecurityServer::GetGidService *getGidService = new SecurityServer::GetGidService;
+        getGidService->Create();
+        manager.RegisterSocketService(getGidService);
+
+        SecurityServer::PrivilegeByPidService *privByPidService = new SecurityServer::PrivilegeByPidService;
+        privByPidService->Create();
+        manager.RegisterSocketService(privByPidService);
+
+        SecurityServer::GetObjectNameService *getObjectNameService = new SecurityServer::GetObjectNameService;
+        getObjectNameService->Create();
+        manager.RegisterSocketService(getObjectNameService);
+
+        SecurityServer::AppPermissionsService *appEnablePermissionsService = new SecurityServer::AppPermissionsService;
+        appEnablePermissionsService->Create();
+        manager.RegisterSocketService(appEnablePermissionsService);
+
+        SecurityServer::PasswordService *pwdService = new SecurityServer::PasswordService;
+        pwdService->Create();
+        manager.RegisterSocketService(pwdService);
+
+        manager.MainLoop();
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+    return 0;
+}
+
diff --git a/src/server/main/server2-main.h b/src/server/main/server2-main.h
new file mode 100644 (file)
index 0000000..c5965a7
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        server-main2.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of security-server2.
+ */
+
+#ifndef _SECURITY_SERVER_SERVER2_
+#define _SECURITY_SERVER_SERVER2_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int server2(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _SECURITY_SERVER_SERVER2_
+
diff --git a/src/server/main/service-thread.h b/src/server/main/service-thread.h
new file mode 100644 (file)
index 0000000..e5989e6
--- /dev/null
@@ -0,0 +1,177 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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-thread.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of threads.
+ */
+
+#ifndef _SECURITY_SERVER_SERVICE_THREAD_
+#define _SECURITY_SERVER_SERVICE_THREAD_
+
+#include <cassert>
+#include <queue>
+#include <mutex>
+#include <thread>
+#include <memory>
+#include <condition_variable>
+
+#include <cstdio>
+
+#include <dpl/exception.h>
+
+#include "generic-event.h"
+
+#define DEFINE_THREAD_EVENT(eventType)                                \
+    void Event(const eventType &event) {                              \
+        SecurityServer::ServiceThread<ParentClassName>::              \
+            Event(event,                                              \
+                  this,                                               \
+                  &ParentClassName::EventInternal##eventType);        \
+    }                                                                 \
+    void EventInternal##eventType(const eventType &event)
+
+#define DECLARE_THREAD_EVENT(eventType, methodName)                   \
+    void Event(const eventType &event) {                              \
+        SecurityServer::ServiceThread<ParentClassName>::              \
+            Event(event,                                              \
+                  this,                                               \
+                  &ParentClassName::methodName);                      \
+    }
+
+namespace SecurityServer {
+
+template <class Service>
+class ServiceThread {
+public:
+    typedef Service ParentClassName;
+    enum class State {
+        NoThread,
+        Work,
+    };
+
+    ServiceThread()
+      : m_state(State::NoThread)
+      , m_quit(false)
+    {}
+
+    void Create() {
+        assert(m_state == State::NoThread);
+        m_thread = std::thread(ThreadLoopStatic, this);
+        m_state = State::Work;
+    }
+
+    void Join() {
+        assert(m_state != State::NoThread);
+        {
+            std::lock_guard<std::mutex> lock(m_eventQueueMutex);
+            m_quit = true;
+            m_waitCondition.notify_one();
+        }
+        m_thread.join();
+        m_state = State::NoThread;
+    }
+
+    virtual ~ServiceThread()
+    {
+        if (m_state != State::NoThread)
+            Join();
+        while (!m_eventQueue.empty()){
+            auto front = m_eventQueue.front();
+            delete front.eventPtr;
+            m_eventQueue.pop();
+        }
+    }
+
+    template <class T>
+    void Event(const T &event,
+               Service *servicePtr,
+               void (Service::*serviceFunction)(const T &))
+    {
+        EventDescription description;
+        description.serviceFunctionPtr =
+            reinterpret_cast<void (Service::*)(void*)>(serviceFunction);
+        description.servicePtr = servicePtr;
+        description.eventFunctionPtr = &ServiceThread::EventCall<T>;
+        description.eventPtr = new T(event);
+        {
+            std::lock_guard<std::mutex> lock(m_eventQueueMutex);
+            m_eventQueue.push(description);
+        }
+        m_waitCondition.notify_one();
+    }
+
+protected:
+
+    struct EventDescription {
+        void (Service::*serviceFunctionPtr)(void *);
+        Service *servicePtr;
+        void (ServiceThread::*eventFunctionPtr)(const EventDescription &event);
+        GenericEvent* eventPtr;
+    };
+
+    template <class T>
+    void EventCall(const EventDescription &desc) {
+        auto fun = reinterpret_cast<void (Service::*)(const T&)>(desc.serviceFunctionPtr);
+        const T& eventLocale = *(static_cast<T*>(desc.eventPtr));
+        (desc.servicePtr->*fun)(eventLocale);
+    }
+
+    static void ThreadLoopStatic(ServiceThread *ptr) {
+        ptr->ThreadLoop();
+    }
+
+    void ThreadLoop(){
+        for (;;) {
+            EventDescription description = {NULL, NULL, NULL, NULL};
+            {
+                std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
+                if (m_quit)
+                    return;
+                if (!m_eventQueue.empty()) {
+                    description = m_eventQueue.front();
+                    m_eventQueue.pop();
+                } else {
+                    m_waitCondition.wait(ulock);
+                }
+            }
+
+            if (description.eventPtr != NULL) {
+                UNHANDLED_EXCEPTION_HANDLER_BEGIN
+                {
+                    (this->*description.eventFunctionPtr)(description);
+                    delete description.eventPtr;
+                }
+                UNHANDLED_EXCEPTION_HANDLER_END
+            }
+        }
+    }
+
+    std::thread m_thread;
+    std::mutex m_eventQueueMutex;
+    std::queue<EventDescription> m_eventQueue;
+    std::condition_variable m_waitCondition;
+
+    State m_state;
+    bool m_quit;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_SERVICE_THREAD_
diff --git a/src/server/main/socket-manager.cpp b/src/server/main/socket-manager.cpp
new file mode 100644 (file)
index 0000000..b62f840
--- /dev/null
@@ -0,0 +1,731 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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-manager.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of SocketManager.
+ */
+
+#include <set>
+
+#include <signal.h>
+#include <sys/select.h>
+#include <sys/signalfd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/smack.h>
+#include <sys/un.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <errno.h>
+#include <time.h>
+
+#include <systemd/sd-daemon.h>
+
+#include <dpl/log/log.h>
+#include <dpl/assert.h>
+
+#include <smack-check.h>
+#include <socket-manager.h>
+
+namespace {
+
+const time_t SOCKET_TIMEOUT = 20;
+
+} // namespace anonymous
+
+namespace SecurityServer {
+
+struct DummyService : public GenericSocketService {
+    ServiceDescriptionVector GetServiceDescription() {
+        return ServiceDescriptionVector();
+    }
+    void Event(const AcceptEvent &event) { (void)event; }
+    void Event(const WriteEvent &event) { (void)event; }
+    void Event(const ReadEvent &event) { (void)event; }
+    void Event(const CloseEvent &event) { (void)event; }
+};
+
+struct SignalService : public GenericSocketService {
+    int GetDescriptor() {
+        LogInfo("set up");
+        sigset_t mask;
+        sigemptyset(&mask);
+        sigaddset(&mask, SIGTERM);
+        if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL))
+            return -1;
+        return signalfd(-1, &mask, 0);
+    }
+
+    ServiceDescriptionVector GetServiceDescription() {
+        return ServiceDescriptionVector();
+    }
+
+    void Event(const AcceptEvent &event) { (void)event; } // not supported
+    void Event(const WriteEvent &event) { (void)event; }  // not supported
+    void Event(const CloseEvent &event) { (void)event; }  // not supported
+
+    void Event(const ReadEvent &event) {
+        LogDebug("Get signal information");
+
+        if(sizeof(struct signalfd_siginfo) != event.rawBuffer.size()) {
+            LogError("Wrong size of signalfd_siginfo struct. Expected: "
+                << sizeof(signalfd_siginfo) << " Get: "
+                << event.rawBuffer.size());
+            return;
+        }
+
+        signalfd_siginfo *siginfo = (signalfd_siginfo*)(&(event.rawBuffer[0]));
+
+        if (siginfo->ssi_signo == SIGTERM) {
+            LogInfo("Got signal: SIGTERM");
+            static_cast<SocketManager*>(m_serviceManager)->MainLoopStop();
+            return;
+        }
+
+        LogInfo("This should not happend. Got signal: " << siginfo->ssi_signo);
+    }
+};
+
+SocketManager::SocketDescription&
+SocketManager::CreateDefaultReadSocketDescription(int sock, bool timeout)
+{
+    if ((int)m_socketDescriptionVector.size() <= sock)
+        m_socketDescriptionVector.resize(sock+20);
+
+    auto &desc = m_socketDescriptionVector[sock];
+    desc.isListen = false;
+    desc.isOpen = true;
+    desc.interfaceID = 0;
+    desc.service = NULL;
+    desc.counter = ++m_counter;
+
+    if (timeout) {
+        desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+        if (false == desc.isTimeout) {
+            Timeout tm;
+            tm.time = desc.timeout;
+            tm.sock = sock;
+            m_timeoutQueue.push(tm);
+        }
+    }
+
+    desc.isTimeout = timeout;
+
+    FD_SET(sock, &m_readSet);
+    m_maxDesc = sock > m_maxDesc ? sock : m_maxDesc;
+    return desc;
+}
+
+SocketManager::SocketManager()
+  : m_counter(0)
+{
+    FD_ZERO(&m_readSet);
+    FD_ZERO(&m_writeSet);
+    if (-1 == pipe(m_notifyMe)) {
+        int err = errno;
+        ThrowMsg(Exception::InitFailed, "Error in pipe: " << strerror(err));
+    }
+    LogInfo("Pipe: Read desc: " << m_notifyMe[0] << " Write desc: " << m_notifyMe[1]);
+
+    auto &desc = CreateDefaultReadSocketDescription(m_notifyMe[0], false);
+    desc.service = new DummyService;
+
+    // std::thread bases on pthread so this should work fine
+    sigset_t set;
+    sigemptyset(&set);
+    sigaddset(&set, SIGPIPE);
+    pthread_sigmask(SIG_BLOCK, &set, NULL);
+
+    // add support for TERM signal (passed from systemd)
+    auto *signalService = new SignalService;
+    signalService->SetSocketManager(this);
+    int filefd = signalService->GetDescriptor();
+    if (-1 == filefd) {
+        LogError("Error in SignalService.GetDescriptor()");
+        delete signalService;
+    } else {
+        auto &desc2 = CreateDefaultReadSocketDescription(filefd, false);
+        desc2.service = signalService;
+        LogInfo("SignalService mounted on " << filefd << " descriptor");
+    }
+}
+
+SocketManager::~SocketManager() {
+    std::set<GenericSocketService*> serviceMap;
+
+    // Find all services. Set is used to remove duplicates.
+    // In this implementation, services are not able to react in any way.
+    for (size_t i=0; i < m_socketDescriptionVector.size(); ++i)
+        if (m_socketDescriptionVector[i].isOpen)
+            serviceMap.insert(m_socketDescriptionVector[i].service);
+
+    // Time to destroy all services.
+    for(auto it = serviceMap.begin(); it != serviceMap.end(); ++it) {
+        LogDebug("delete " << (void*)(*it));
+        delete *it;
+    }
+
+    for (size_t i = 0; i < m_socketDescriptionVector.size(); ++i)
+        if (m_socketDescriptionVector[i].isOpen)
+            close(i);
+
+    // All socket except one were closed. Now pipe input must be closed.
+    close(m_notifyMe[1]);
+}
+
+void SocketManager::ReadyForAccept(int sock) {
+    struct sockaddr_un clientAddr;
+    unsigned int clientLen = sizeof(clientAddr);
+    int client = accept4(sock, (struct sockaddr*) &clientAddr, &clientLen, SOCK_NONBLOCK);
+//    LogInfo("Accept on sock: " << sock << " Socket opended: " << client);
+    if (-1 == client) {
+        int err = errno;
+        LogDebug("Error in accept: " << strerror(err));
+        return;
+    }
+
+    auto &desc = CreateDefaultReadSocketDescription(client, true);
+    desc.interfaceID = m_socketDescriptionVector[sock].interfaceID;
+    desc.service = m_socketDescriptionVector[sock].service;
+    desc.useSendMsg = m_socketDescriptionVector[sock].useSendMsg;
+
+    GenericSocketService::AcceptEvent event;
+    event.connectionID.sock = client;
+    event.connectionID.counter = desc.counter;
+    event.interfaceID = desc.interfaceID;
+    desc.service->Event(event);
+}
+
+void SocketManager::ReadyForRead(int sock) {
+    if (m_socketDescriptionVector[sock].isListen) {
+        ReadyForAccept(sock);
+        return;
+    }
+
+    GenericSocketService::ReadEvent event;
+    event.connectionID.sock = sock;
+    event.connectionID.counter = m_socketDescriptionVector[sock].counter;
+    event.rawBuffer.resize(4096);
+
+    auto &desc = m_socketDescriptionVector[sock];
+    desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+
+    ssize_t size = read(sock, &event.rawBuffer[0], 4096);
+
+    if (size == 0) {
+        CloseSocket(sock);
+    } else if (size >= 0) {
+        event.rawBuffer.resize(size);
+        desc.service->Event(event);
+    } else if (size == -1) {
+        int err = errno;
+        switch(err) {
+            case EAGAIN:
+            case EINTR:
+                break;
+            default:
+                LogDebug("Reading sock error: " << strerror(err));
+                CloseSocket(sock);
+        }
+    }
+}
+
+void SocketManager::ReadyForSendMsg(int sock) {
+    auto &desc = m_socketDescriptionVector[sock];
+
+    if (desc.sendMsgDataQueue.empty()) {
+         FD_CLR(sock, &m_writeSet);
+         return;
+    }
+
+    auto data = desc.sendMsgDataQueue.front();
+    ssize_t result = sendmsg(sock, data.getMsghdr(), data.flags());
+
+    if (result == -1) {
+        int err = errno;
+        switch(err) {
+        case EAGAIN:
+        case EINTR:
+            break;
+        case EPIPE:
+        default:
+            LogDebug("Error during send: " << strerror(err));
+            CloseSocket(sock);
+            break;
+        }
+        return;
+    } else {
+        desc.sendMsgDataQueue.pop();
+    }
+
+    if (desc.sendMsgDataQueue.empty()) {
+        FD_CLR(sock, &m_writeSet);
+    }
+
+    desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+
+    GenericSocketService::WriteEvent event;
+    event.connectionID.sock = sock;
+    event.connectionID.counter = desc.counter;
+    event.size = result;
+    event.left = desc.sendMsgDataQueue.size();
+
+    desc.service->Event(event);
+}
+
+void SocketManager::ReadyForWriteBuffer(int sock) {
+    auto &desc = m_socketDescriptionVector[sock];
+    size_t size = desc.rawBuffer.size();
+    ssize_t result = write(sock, &desc.rawBuffer[0], size);
+    if (result == -1) {
+        int err = errno;
+        switch(err) {
+        case EAGAIN:
+        case EINTR:
+            // select will trigger write once again, nothing to do
+            break;
+        case EPIPE:
+        default:
+            LogDebug("Error during write: " << strerror(err));
+            CloseSocket(sock);
+            break;
+        }
+        return; // We do not want to propagate error to next layer
+    }
+
+    desc.rawBuffer.erase(desc.rawBuffer.begin(), desc.rawBuffer.begin()+result);
+
+    desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+
+    if (desc.rawBuffer.empty())
+        FD_CLR(sock, &m_writeSet);
+
+    GenericSocketService::WriteEvent event;
+    event.connectionID.sock = sock;
+    event.connectionID.counter = desc.counter;
+    event.size = result;
+    event.left = desc.rawBuffer.size();
+
+    desc.service->Event(event);
+}
+
+void SocketManager::ReadyForWrite(int sock) {
+    m_socketDescriptionVector[sock].useSendMsg ?
+        ReadyForSendMsg(sock) : ReadyForWriteBuffer(sock);
+}
+
+void SocketManager::MainLoop() {
+    // remove evironment values passed by systemd
+    // uncomment it after removing old security-server code
+    // sd_listen_fds(1);
+
+    // Daemon is ready to work.
+    sd_notify(0, "READY=1");
+
+    m_working = true;
+    while(m_working) {
+        fd_set readSet = m_readSet;
+        fd_set writeSet = m_writeSet;
+
+        timeval localTempTimeout;
+        timeval *ptrTimeout = &localTempTimeout;
+
+        // I need to extract timeout from priority_queue.
+        // Timeout in priority_queue may be deprecated.
+        // I need to find some actual one.
+        while(!m_timeoutQueue.empty()) {
+            auto &top = m_timeoutQueue.top();
+            auto &desc = m_socketDescriptionVector[top.sock];
+
+            if (top.time == desc.timeout) {
+                // This timeout matches timeout from socket.
+                // It can be used.
+                break;
+            } else {
+                // This socket was used after timeout in priority queue was set up.
+                // We need to update timeout and find some useable one.
+                Timeout tm = { desc.timeout , top.sock};
+                m_timeoutQueue.pop();
+                m_timeoutQueue.push(tm);
+            }
+        }
+
+        if (m_timeoutQueue.empty()) {
+            LogDebug("No usaable timeout found.");
+            ptrTimeout = NULL; // select will wait without timeout
+        } else {
+            time_t currentTime = time(NULL);
+            auto &pqTimeout = m_timeoutQueue.top();
+
+            // 0 means that select won't block and socket will be closed ;-)
+            ptrTimeout->tv_sec =
+              currentTime < pqTimeout.time ? pqTimeout.time - currentTime : 0;
+            ptrTimeout->tv_usec = 0;
+//            LogDebug("Set up timeout: " << (int)ptrTimeout->tv_sec
+//                << " seconds. Socket: " << pqTimeout.sock);
+        }
+
+        int ret = select(m_maxDesc+1, &readSet, &writeSet, NULL, ptrTimeout);
+
+        if (0 == ret) { // timeout
+            Assert(!m_timeoutQueue.empty());
+
+            Timeout pqTimeout = m_timeoutQueue.top();
+            m_timeoutQueue.pop();
+
+            auto &desc = m_socketDescriptionVector[pqTimeout.sock];
+
+            if (!desc.isTimeout || !desc.isOpen) {
+                // Connection was closed. Timeout is useless...
+                desc.isTimeout = false;
+                continue;
+            }
+
+            if (pqTimeout.time < desc.timeout) {
+                // Is it possible?
+                // This socket was used after timeout. We need to update timeout.
+                pqTimeout.time = desc.timeout;
+                m_timeoutQueue.push(pqTimeout);
+                continue;
+            }
+
+            // timeout from m_timeoutQueue matches with socket.timeout
+            // and connection is open. Time to close it!
+            // Putting new timeout in queue here is pointless.
+            desc.isTimeout = false;
+            CloseSocket(pqTimeout.sock);
+
+            // All done. Now we should process next select ;-)
+            continue;
+        }
+
+        if (-1 == ret) {
+            switch(errno) {
+            case EINTR:
+                LogDebug("EINTR in select");
+                break;
+            default:
+                int err = errno;
+                LogError("Error in select: " << strerror(err));
+                return;
+            }
+            continue;
+        }
+        for(int i = 0; i<m_maxDesc+1 && ret; ++i) {
+            if (FD_ISSET(i, &readSet)) {
+                ReadyForRead(i);
+                --ret;
+            }
+            if (FD_ISSET(i, &writeSet)) {
+                ReadyForWrite(i);
+                --ret;
+            }
+        }
+        ProcessQueue();
+    }
+}
+
+void SocketManager::MainLoopStop()
+{
+    m_working = false;
+    NotifyMe();
+}
+
+int SocketManager::GetSocketFromSystemD(
+    const GenericSocketService::ServiceDescription &desc)
+{
+    int fd;
+
+    // TODO optimalization - do it once in object constructor
+    //                       and remember all information path->sockfd
+    int n = sd_listen_fds(0);
+
+    LogInfo("sd_listen_fds returns: " << n);
+
+    if (n < 0) {
+        LogError("Error in sd_listend_fds");
+        ThrowMsg(Exception::InitFailed, "Error in sd_listend_fds");
+    }
+
+    for(fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) {
+        if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1,
+                                  desc.serviceHandlerPath.c_str(), 0))
+        {
+            LogInfo("Useable socket " << desc.serviceHandlerPath <<
+                " was passed by SystemD under descriptor " << fd);
+            return fd;
+        }
+    }
+    LogInfo("No useable sockets were passed by systemd.");
+    return -1;
+}
+
+int SocketManager::CreateDomainSocketHelp(
+    const GenericSocketService::ServiceDescription &desc)
+{
+    int sockfd;
+
+    if (-1 == (sockfd = socket(AF_UNIX, SOCK_STREAM, 0))) {
+        int err = errno;
+        LogError("Error in socket: " << strerror(err));
+        ThrowMsg(Exception::InitFailed, "Error in socket: " << strerror(err));
+    }
+
+    if (smack_check()) {
+        LogInfo("Set up smack label: " << desc.smackLabel);
+
+        if (0 != smack_fsetlabel(sockfd, desc.smackLabel.c_str(), SMACK_LABEL_IPIN)) {
+            LogError("Error in smack_fsetlabel");
+            ThrowMsg(Exception::InitFailed, "Error in smack_fsetlabel");
+        }
+    } else {
+        LogInfo("No smack on platform. Socket won't be securied with smack label!");
+    }
+
+    int flags;
+    if (-1 == (flags = fcntl(sockfd, F_GETFL, 0)))
+        flags = 0;
+
+    if (-1 == fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)) {
+        int err = errno;
+        close(sockfd);
+        LogError("Error in fcntl: " << strerror(err));
+        ThrowMsg(Exception::InitFailed, "Error in fcntl: " << strerror(err));
+    }
+
+    sockaddr_un serverAddress;
+    memset(&serverAddress, 0, sizeof(serverAddress));
+    serverAddress.sun_family = AF_UNIX;
+    strcpy(serverAddress.sun_path, desc.serviceHandlerPath.c_str());
+    unlink(serverAddress.sun_path);
+
+    mode_t originalUmask;
+    originalUmask = umask(0);
+
+    if (-1 == bind(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) {
+        int err = errno;
+        close(sockfd);
+        LogError("Error in bind: " << strerror(err));
+        ThrowMsg(Exception::InitFailed, "Error in bind: " << strerror(err));
+    }
+
+    umask(originalUmask);
+
+    if (-1 == listen(sockfd, 5)) {
+        int err = errno;
+        close(sockfd);
+        LogError("Error in listen: " << strerror(err));
+        ThrowMsg(Exception::InitFailed, "Error in listen: " << strerror(err));
+    }
+
+    return sockfd;
+}
+
+void SocketManager::CreateDomainSocket(
+    GenericSocketService *service,
+    const GenericSocketService::ServiceDescription &desc)
+{
+    int sockfd = GetSocketFromSystemD(desc);
+    if (-1 == sockfd)
+        sockfd = CreateDomainSocketHelp(desc);
+
+    auto &description = CreateDefaultReadSocketDescription(sockfd, false);
+
+    description.isListen = true;
+    description.interfaceID = desc.interfaceID;
+    description.useSendMsg = desc.useSendMsg;
+    description.service = service;
+
+    LogDebug("Listen on socket: " << sockfd <<
+        " Handler: " << desc.serviceHandlerPath.c_str());
+}
+
+void SocketManager::RegisterSocketService(GenericSocketService *service) {
+    service->SetSocketManager(this);
+    auto serviceVector = service->GetServiceDescription();
+    Try {
+        for (auto iter = serviceVector.begin(); iter != serviceVector.end(); ++iter)
+            CreateDomainSocket(service, *iter);
+    } Catch (Exception::Base) {
+        for (int i =0; i < (int)m_socketDescriptionVector.size(); ++i)
+        {
+            auto &desc = m_socketDescriptionVector[i];
+            if (desc.service == service && desc.isOpen) {
+                close(i);
+                desc.isOpen = false;
+            }
+        }
+        ReThrow(Exception::Base);
+    }
+}
+
+void SocketManager::Close(ConnectionID connectionID) {
+    {
+        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
+        m_closeQueue.push(connectionID);
+    }
+    NotifyMe();
+}
+
+void SocketManager::Write(ConnectionID connectionID, const RawBuffer &rawBuffer) {
+    WriteBuffer buffer;
+    buffer.connectionID = connectionID;
+    buffer.rawBuffer = rawBuffer;
+    {
+        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
+        m_writeBufferQueue.push(buffer);
+    }
+    NotifyMe();
+}
+
+void SocketManager::Write(ConnectionID connectionID, const SendMsgData &sendMsgData) {
+    WriteData data;
+    data.connectionID = connectionID;
+    data.sendMsgData = sendMsgData;
+    {
+        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
+        m_writeDataQueue.push(data);
+    }
+    NotifyMe();
+}
+
+void SocketManager::NotifyMe() {
+    TEMP_FAILURE_RETRY(write(m_notifyMe[1], "You have message ;-)", 1));
+}
+
+void SocketManager::ProcessQueue() {
+    WriteBuffer buffer;
+    WriteData data;
+    {
+        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
+        while (!m_writeBufferQueue.empty()) {
+            buffer = m_writeBufferQueue.front();
+            m_writeBufferQueue.pop();
+
+            auto &desc = m_socketDescriptionVector[buffer.connectionID.sock];
+
+            if (!desc.isOpen) {
+                LogDebug("Received packet for write but connection is closed. Packet ignored!");
+                continue;
+            }
+
+            if (desc.counter != buffer.connectionID.counter)
+            {
+                LogDebug("Received packet for write but counter is broken. Packet ignored!");
+                continue;
+            }
+
+            if (desc.useSendMsg) {
+                LogError("Some service tried to push rawdata to socket that usees sendmsg!");
+                continue;
+            }
+
+            std::copy(
+                buffer.rawBuffer.begin(),
+                buffer.rawBuffer.end(),
+                std::back_inserter(desc.rawBuffer));
+
+            FD_SET(buffer.connectionID.sock, &m_writeSet);
+        }
+
+        while(!m_writeDataQueue.empty()) {
+            data = m_writeDataQueue.front();
+            m_writeDataQueue.pop();
+
+            auto &desc = m_socketDescriptionVector[data.connectionID.sock];
+
+            if (!desc.isOpen) {
+                LogDebug("Received packet for sendmsg but connection is closed. Packet ignored!");
+                continue;
+            }
+
+            if (desc.counter != data.connectionID.counter)
+            {
+                LogDebug("Received packet for write but counter is broken. Packet ignored!");
+                continue;
+            }
+
+            if (!desc.useSendMsg) {
+                LogError("Some service tries to push SendMsgData to socket that uses write!");
+                continue;
+            }
+
+            desc.sendMsgDataQueue.push(data.sendMsgData);
+
+            FD_SET(data.connectionID.sock, &m_writeSet);
+        }
+    }
+
+    while (1) {
+        ConnectionID connection;
+        {
+            std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
+            if (m_closeQueue.empty())
+                return;
+            connection = m_closeQueue.front();
+            m_closeQueue.pop();
+        }
+
+        if (!m_socketDescriptionVector[connection.sock].isOpen)
+            continue;
+
+        if (connection.counter != m_socketDescriptionVector[connection.sock].counter)
+            continue;
+
+        CloseSocket(connection.sock);
+    }
+}
+
+void SocketManager::CloseSocket(int sock) {
+//    LogInfo("Closing socket: " << sock);
+    auto &desc = m_socketDescriptionVector[sock];
+
+    if (!(desc.isOpen)) {
+        // This may happend when some information was waiting for write to the
+        // socket and in the same time socket was closed by the client.
+        LogError("Socket " << sock << " is not open. Nothing to do!");
+        return;
+    }
+
+    GenericSocketService::CloseEvent event;
+    event.connectionID.sock = sock;
+    event.connectionID.counter = desc.counter;
+    auto service = desc.service;
+
+    desc.isOpen = false;
+    desc.service = NULL;
+    desc.interfaceID = -1;
+    desc.rawBuffer.clear();
+    while(!desc.sendMsgDataQueue.empty())
+        desc.sendMsgDataQueue.pop();
+
+    if (service)
+        service->Event(event);
+    else
+        LogError("Critical! Service is NULL! This should never happend!");
+
+    TEMP_FAILURE_RETRY(close(sock));
+    FD_CLR(sock, &m_readSet);
+    FD_CLR(sock, &m_writeSet);
+}
+
+} // namespace SecurityServer
diff --git a/src/server/main/socket-manager.h b/src/server/main/socket-manager.h
new file mode 100644 (file)
index 0000000..b7b733c
--- /dev/null
@@ -0,0 +1,135 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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-manager.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       SocketManager implementation.
+ */
+
+#ifndef _SECURITY_SERVER_SOCKET_MANAGER_
+#define _SECURITY_SERVER_SOCKET_MANAGER_
+
+#include <vector>
+#include <queue>
+#include <string>
+#include <mutex>
+#include <thread>
+
+#include <dpl/exception.h>
+
+#include <generic-socket-manager.h>
+
+namespace SecurityServer {
+
+class SocketManager : public GenericSocketManager {
+public:
+    class Exception {
+    public:
+        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, InitFailed)
+    };
+    SocketManager();
+    virtual ~SocketManager();
+    virtual void MainLoop();
+    virtual void MainLoopStop();
+
+    virtual void RegisterSocketService(GenericSocketService *service);
+    virtual void Close(ConnectionID connectionID);
+    virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer);
+    virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData);
+
+protected:
+    void CreateDomainSocket(
+        GenericSocketService *service,
+        const GenericSocketService::ServiceDescription &desc);
+    int CreateDomainSocketHelp(
+        const GenericSocketService::ServiceDescription &desc);
+    int GetSocketFromSystemD(
+        const GenericSocketService::ServiceDescription &desc);
+
+    void ReadyForRead(int sock);
+    void ReadyForWrite(int sock);
+    void ReadyForWriteBuffer(int sock);
+    void ReadyForSendMsg(int sock);
+    void ReadyForAccept(int sock);
+    void ProcessQueue(void);
+    void NotifyMe(void);
+    void CloseSocket(int sock);
+
+    struct SocketDescription {
+        bool isListen;
+        bool isOpen;
+        bool isTimeout;
+        bool useSendMsg;
+        InterfaceID interfaceID;
+        GenericSocketService *service;
+        time_t timeout;
+        RawBuffer rawBuffer;
+        std::queue<SendMsgData> sendMsgDataQueue;
+        int counter;
+
+        SocketDescription()
+          : isListen(false)
+          , isOpen(false)
+          , isTimeout(false)
+          , useSendMsg(false)
+          , interfaceID(-1)
+          , service(NULL)
+        {}
+    };
+
+    SocketDescription& CreateDefaultReadSocketDescription(int sock, bool timeout);
+
+    typedef std::vector<SocketDescription> SocketDescriptionVector;
+
+    struct WriteBuffer {
+        ConnectionID connectionID;
+        RawBuffer rawBuffer;
+    };
+
+    struct WriteData {
+        ConnectionID connectionID;
+        SendMsgData sendMsgData;
+    };
+
+    struct Timeout {
+        time_t time;
+        int sock;
+        bool operator<(const Timeout &second) const {
+            return time > second.time; // mininum first!
+        }
+    };
+
+    SocketDescriptionVector m_socketDescriptionVector;
+    fd_set m_readSet;
+    fd_set m_writeSet;
+    int m_maxDesc;
+    bool m_working;
+    std::mutex m_eventQueueMutex;
+    std::queue<WriteBuffer> m_writeBufferQueue;
+    std::queue<WriteData> m_writeDataQueue;
+    std::queue<ConnectionID> m_closeQueue;
+    int m_notifyMe[2];
+    int m_counter;
+    std::priority_queue<Timeout> m_timeoutQueue;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_SOCKET_MANAGER_
diff --git a/src/server/security-server-main.c b/src/server/security-server-main.c
deleted file mode 100644 (file)
index 8f7d531..0000000
+++ /dev/null
@@ -1,582 +0,0 @@
-/*
- * security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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
- *
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/smack.h>
-#include <errno.h>
-#include <signal.h>
-#include <pthread.h>
-#include <limits.h>
-#include <fcntl.h>
-#include <sys/smack.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/wait.h>
-#include <poll.h>
-#include <grp.h>
-#include <stdint.h>
-
-#include <server2-main.h>
-
-#include <privilege-control.h>
-
-#include "security-server-common.h"
-#include "security-server-comm.h"
-#include "security-server-util.h"
-#include "smack-check.h"
-
-//definitions of security-server API labels
-#define API_PASSWD_SET   "security-server::api-password-set"
-#define API_PASSWD_CHECK "security-server::api-password-check"
-#define API_DATA_SHARE   "security-server::api-data-share"
-#define API_MIDDLEWARE   "security-server::api-middleware"
-#define API_FREE_ACCESS  "*"
-
-//required rule type
-#define API_RULE_REQUIRED "w"
-
-int thread_status[SECURITY_SERVER_NUM_THREADS];
-struct security_server_thread_param {
-    int client_sockfd;
-    int server_sockfd;
-    int thread_status;
-};
-
-
-/*
- * Searches for group ID by given group name
- */
-
-int search_gid(const char *obj)
-{
-    int ret = 0;
-    struct group *grpbuf = NULL;
-    struct group grp;
-    char *buf = NULL;
-    char *bigger_buf = NULL;
-    long int max_buf_size = 0;
-
-    /*
-     * The maximum needed size for buf can be found using sysconf(3) with the argument _SC_GETGR_R_SIZE_MAX
- * If _SC_GETGR_R_SIZE_MAX is not returned we set max_buf_size to 1024 bytes. Enough to store few groups.
-     */
-    max_buf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
-    if (max_buf_size == -1)
-        max_buf_size = 1024;
-
-    buf = malloc((size_t)max_buf_size);
-    if (buf == NULL)
-    {
-        ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-        SEC_SVR_ERR("Out Of Memory");
-        goto error;
-    }
-
-    /*
-     * There can be some corner cases when for example user is assigned to a lot of groups.
-     * In that case if buffer is to small getgrnam_r will return ERANGE error.
-     * Solution could be calling getgrnam_r with bigger buffer until it's enough big.
-     */
-    while ((ret = getgrnam_r(obj, &grp, buf, (size_t)max_buf_size, &grpbuf)) == ERANGE) {
-        max_buf_size *= 2;
-
-        bigger_buf = realloc(buf, (size_t)max_buf_size);
-        if (bigger_buf == NULL) {
-            ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
-            SEC_SVR_ERR("Out Of Memory");
-            goto error;
-        }
-
-        buf = bigger_buf;
-    }
-
-    if (ret != 0)
-    {
-        ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
-        SEC_SVR_ERR("getgrnam_r failed with error %s\n", strerror(errno));
-        goto error;
-    } else if (grpbuf == NULL) {
-        ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
-        SEC_SVR_ERR("Cannot find gid for group %s\n", obj);
-        goto error;
-    }
-
-    ret = grpbuf->gr_gid;
-
-error:
-    free(buf);
-    return ret;
-}
-
-/* Signal handler for processes */
-static void security_server_sig_child(int signo, siginfo_t *info, void *data)
-{
-    int status;
-    pid_t child_pid;
-    pid_t child_pgid;
-
-    (void)signo;
-    (void)data;
-
-    child_pgid = getpgid(info->si_pid);
-    SEC_SVR_DBG("Signal handler: dead_pid=%d, pgid=%d",info->si_pid,child_pgid);
-
-    while ((child_pid = waitpid(-1, &status, WNOHANG)) > 0) {
-        if (child_pid == child_pgid)
-            killpg(child_pgid,SIGKILL);
-    }
-
-    return;
-}
-
-// int process_object_name_request(int sockfd)
-// {
-//     int retval, client_pid, requested_privilege;
-//     char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
-
-//     /* Authenticate client */
-//     retval = authenticate_client_middleware(sockfd, &client_pid);
-//     if (retval != SECURITY_SERVER_SUCCESS)
-//     {
-//         SEC_SVR_ERR("%s", "Client Authentication Failed");
-//         retval = send_generic_response(sockfd,
-//             SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-//             SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-//         if (retval != SECURITY_SERVER_SUCCESS)
-//         {
-//             SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-//         }
-//         goto error;
-//     }
-
-//     /* Receive GID */
-//     retval = TEMP_FAILURE_RETRY(read(sockfd, &requested_privilege, sizeof(requested_privilege)));
-//     if (retval < (int)sizeof(requested_privilege))
-//     {
-//         SEC_SVR_ERR("%s", "Receiving request failed");
-//         retval = send_generic_response(sockfd,
-//             SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-//             SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-//         if (retval != SECURITY_SERVER_SUCCESS)
-//         {
-//             SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-//         }
-//         goto error;
-//     }
-
-//     /* Search from /etc/group */
-//     retval = search_object_name(requested_privilege,
-//         object_name,
-//         SECURITY_SERVER_MAX_OBJ_NAME);
-//     if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
-//     {
-//         /* It's not exist */
-//         SEC_SVR_ERR("There is no such object for gid [%d]", requested_privilege);
-//         retval = send_generic_response(sockfd,
-//             SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-//             SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
-//         if (retval != SECURITY_SERVER_SUCCESS)
-//         {
-//             SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-//         }
-//         goto error;
-//     }
-//     if (retval != SECURITY_SERVER_SUCCESS)
-//     {
-//         /* Error occurred */
-//         SEC_SVR_ERR("Error on searching object name [%d]", retval);
-//         retval = send_generic_response(sockfd,
-//             SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
-//             SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-//         if (retval != SECURITY_SERVER_SUCCESS)
-//         {
-//             SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-//         }
-//         goto error;
-//     }
-
-//     /* We found */
-//     SECURE_SLOGD("We found object: %s", object_name);
-//     retval = send_object_name(sockfd, object_name);
-//     if (retval != SECURITY_SERVER_SUCCESS)
-//     {
-//         SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-//     }
-// error:
-//     return retval;
-// }
-
-int process_gid_request(int sockfd, int msg_len)
-{
-    int retval, client_pid;
-    char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
-    /* Authenticate client as middleware daemon */
-    retval = authenticate_client_middleware(sockfd, &client_pid);
-    if (retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_ERR("%s", "Client authentication failed");
-        retval = send_generic_response(sockfd,
-            SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
-        if (retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-    if (msg_len >= SECURITY_SERVER_MAX_OBJ_NAME)
-    {
-        /* Too big ojbect name */
-        SECURE_SLOGE("%s", "Object name is too big");
-        retval = send_generic_response(sockfd,
-            SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-        if (retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    /* Receive group name */
-    retval = TEMP_FAILURE_RETRY(read(sockfd, object_name, msg_len));
-    if (retval < msg_len)
-    {
-        SECURE_SLOGE("%s", "Failed to read object name");
-        retval = send_generic_response(sockfd,
-            SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-        if (retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-    object_name[msg_len] = 0;
-
-    /* Search /etc/group for the given group name */
-    retval = search_gid(object_name);
-    if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
-    {
-        /* Not exist */
-        SECURE_SLOGD("The object [%s] is not exist", object_name);
-        retval = send_generic_response(sockfd,
-            SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
-        if (retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-        }
-        goto error;
-    }
-
-    if (retval < 0)
-    {
-        /* Error occurred */
-        SEC_SVR_ERR("Cannot send the response. %d", retval);
-        retval = send_generic_response(sockfd,
-            SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
-        if (retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-        }
-
-        goto error;
-    }
-    /* We found */
-    retval = send_gid(sockfd, retval);
-    if (retval != SECURITY_SERVER_SUCCESS)
-    {
-        SEC_SVR_ERR("ERROR: Cannot gid response: %d", retval);
-    }
-error:
-    return retval;
-}
-
-int client_has_access(int sockfd, const char *object)
-{
-    char *label = NULL;
-    int ret = 0;
-    int pid = -1;
-    int uid = -1;
-    int retval;
-    struct ucred socopt;
-    unsigned int socoptSize = sizeof(socopt);
-
-    if (smack_check())
-    {
-        retval = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &socopt, &socoptSize);
-        if (retval != 0) {
-            SEC_SVR_DBG("%s", "Error on getsockopt");
-            return 0;
-        }
-        //now we have PID in sockopt.pid
-
-        if (smack_new_label_from_socket(sockfd, &label) < 0) {
-            SEC_SVR_ERR("%s", "Error on smack_new_label_from_socket");
-            label = NULL;
-        }
-
-        if (0 >= (ret = smack_pid_have_access(socopt.pid, object, "rw"))) {
-            ret = 0;
-        }
-    }
-
-    if (SECURITY_SERVER_SUCCESS == authenticate_client_application(sockfd, &pid, &uid))
-        SECURE_SLOGD("SS_SMACK: caller_pid=%d, subject=%s, object=%s, access=rw, result=%d",
-            pid, label, object, ret);
-
-    free(label);
-    return ret;
-}
-
-void *security_server_thread(void *param)
-{
-    int client_sockfd = -1;
-    int retval;
-    basic_header basic_hdr;
-    struct security_server_thread_param *my_param;
-
-    my_param = (struct security_server_thread_param*) param;
-    client_sockfd = my_param->client_sockfd;
-
-    /* Receive request header */
-    retval = recv_hdr(client_sockfd, &basic_hdr);
-    if (retval == SECURITY_SERVER_ERROR_TIMEOUT || retval == SECURITY_SERVER_ERROR_RECV_FAILED
-        || retval == SECURITY_SERVER_ERROR_SOCKET)
-    {
-        SEC_SVR_ERR("Receiving header error [%d]",retval);
-        close(client_sockfd);
-        client_sockfd = -1;
-        goto error;;
-    }
-
-    if (retval != SECURITY_SERVER_SUCCESS)
-    {
-        /* Response */
-        SEC_SVR_ERR("Receiving header error [%d]",retval);
-        retval = send_generic_response(client_sockfd,
-            SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-        if (retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-            goto error;
-        }
-        safe_server_sock_close(client_sockfd);
-        client_sockfd = -1;
-        goto error;
-    }
-
-    //TODO: Below authorize_SS_API_caller_socket() is used for authorize API caller by SMACK,
-    //      at the moment return value is not checked and each access is allowed.
-    //      If we realy want to restrict access it must be changed in future.
-
-    /* Act different for request message ID */
-    switch (basic_hdr.msg_id)
-    {
-        // case SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST:
-        //     SECURE_SLOGD("%s", "Get object name request received");
-        //     authorize_SS_API_caller_socket(client_sockfd, API_MIDDLEWARE, API_RULE_REQUIRED);
-        //     process_object_name_request(client_sockfd);
-        //     break;
-
-        case SECURITY_SERVER_MSG_TYPE_GID_REQUEST:
-            SEC_SVR_DBG("%s", "Get GID received");
-            authorize_SS_API_caller_socket(client_sockfd, API_MIDDLEWARE, API_RULE_REQUIRED);
-            process_gid_request(client_sockfd, (int)basic_hdr.msg_len);
-            break;
-
-        default:
-            SEC_SVR_ERR("Unknown msg ID :%d", basic_hdr.msg_id);
-            /* Unknown message ID */
-            retval = send_generic_response(client_sockfd,
-            SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
-            SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
-            if (retval != SECURITY_SERVER_SUCCESS)
-            {
-                SEC_SVR_ERR("ERROR: Cannot send generic response: %d", retval);
-            }
-            break;
-    }
-
-    if (client_sockfd > 0)
-    {
-        safe_server_sock_close(client_sockfd);
-        client_sockfd = -1;
-    }
-
-error:
-    if (client_sockfd > 0)
-        close(client_sockfd);
-    thread_status[my_param->thread_status] = 0;
-    pthread_detach(pthread_self());
-    pthread_exit(NULL);
-}
-
-void *security_server_main_thread(void *data)
-{
-    int server_sockfd = 0, retval, client_sockfd = -1, rc;
-    struct sigaction act, dummy;
-    pthread_t threads[SECURITY_SERVER_NUM_THREADS];
-    struct security_server_thread_param param[SECURITY_SERVER_NUM_THREADS];
-
-    (void)data;
-
-    SECURE_SLOGD("%s", "Starting Security Server main thread");
-
-    /* security server must be executed by root */
-    if (getuid() != 0)
-    {
-        fprintf(stderr, "%s\n", "You are not root. exiting...");
-        goto error;
-    }
-
-    for (retval = 0; retval < SECURITY_SERVER_NUM_THREADS; retval++)
-        thread_status[retval] = 0;
-
-    /* Create and bind a Unix domain socket */
-    if(SECURITY_SERVER_SUCCESS != get_socket_from_systemd(&server_sockfd))
-    {
-        SEC_SVR_ERR("%s", "Error in get_socket_from_systemd");
-        retval = create_new_socket(&server_sockfd);
-        if (retval != SECURITY_SERVER_SUCCESS)
-        {
-            SEC_SVR_ERR("%s", "cannot create socket. exiting...");
-            goto error;
-        }
-
-        if (listen(server_sockfd, 5) < 0)
-        {
-            SEC_SVR_ERR("%s", "listen() failed. exiting...");
-            goto error;
-        }
-    } else {
-        SEC_SVR_ERR("%s", "Socket was passed by systemd");
-    }
-
-    /* Init signal handler */
-    act.sa_handler = NULL;
-    act.sa_sigaction = security_server_sig_child;
-    sigemptyset(&act.sa_mask);
-    act.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
-
-    if (sigaction(SIGCHLD, &act, &dummy) < 0)
-    {
-        SEC_SVR_ERR("%s", "cannot change session");
-    }
-
-    while (1)
-    {
-        /* Accept a new client */
-        if (client_sockfd < 0)
-            client_sockfd = accept_client(server_sockfd);
-
-        if (client_sockfd == SECURITY_SERVER_ERROR_TIMEOUT)
-            continue;
-        if (client_sockfd < 0)
-            goto error;
-        SEC_SVR_DBG("Server: new connection has been accepted: %d", client_sockfd);
-        retval = 0;
-        while (1)
-        {
-            if (thread_status[retval] == 0)
-            {
-                thread_status[retval] = 1;
-                param[retval].client_sockfd = client_sockfd;
-                param[retval].server_sockfd = server_sockfd;
-                param[retval].thread_status = retval;
-                SEC_SVR_DBG("Server: Creating a new thread: %d", retval);
-                rc = pthread_create(&threads[retval], NULL, security_server_thread, (void*)&param[retval]);
-                if (rc)
-                {
-                    SEC_SVR_ERR("Error: Server: Cannot create thread:%d", rc);
-                    goto error;
-                }
-                break;
-            }
-            retval++;
-            if (retval >= SECURITY_SERVER_NUM_THREADS)
-                retval = 0;
-        }
-        client_sockfd = -1;
-    }
-error:
-    if (server_sockfd > 0)
-        close(server_sockfd);
-
-    pthread_detach(pthread_self());
-    pthread_exit(NULL);
-}
-
-ssize_t read_wrapper(int sockfd, void *buffer, size_t len)
-{
-    unsigned char *buff = (unsigned char*)buffer;
-    ssize_t done = 0;
-    while (done < (int)len) {
-        struct pollfd fds = { sockfd, POLLIN, 0};
-        if (0 >= poll(&fds, 1, 1000))
-            break;
-        ssize_t ret = read(sockfd, buff + done, len - done);
-        if (0 < ret) {
-            done += ret;
-            continue;
-        }
-        if (0 == ret)
-            break;
-        if (-1 == ret && EAGAIN != errno && EINTR != errno)
-            break;
-    }
-    return done;
-}
-
-int main(int argc, char *argv[])
-{
-    int res;
-    pthread_t main_thread;
-
-    (void)argc;
-    (void)argv;
-
-    sigset_t mask;
-    sigemptyset(&mask);
-    sigaddset(&mask, SIGTERM);
-    sigaddset(&mask, SIGPIPE);
-    if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL)) {
-        SEC_SVR_ERR("Error in pthread_sigmask");
-    }
-
-    if (0 != (res = pthread_create(&main_thread, NULL, security_server_main_thread, NULL))) {
-        SEC_SVR_ERR("Error: Server: Cannot create main security server thread: %s", strerror(res));
-        return -1;
-    }
-
-    server2();
-    exit(0);
-    return 0;
-}
-
diff --git a/src/server/service/app-permissions.cpp b/src/server/service/app-permissions.cpp
new file mode 100644 (file)
index 0000000..ff666bc
--- /dev/null
@@ -0,0 +1,267 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        app-permissions.cpp
+ * @author      Pawel Polawski (pawel.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This function contain implementation of security_server_app_enable_permissions
+ *              and security_server_app_disable_permissions on server side
+ */
+
+#include <memory>
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+#include <privilege-control.h>
+
+#include <sys/smack.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <app-permissions.h>
+#include <protocols.h>
+#include <security-server.h>
+#include <privilege-control.h>
+
+namespace {
+
+int privilegeToSecurityServerError(int error) {
+    switch (error) {
+    case PC_OPERATION_SUCCESS:  return SECURITY_SERVER_API_SUCCESS;
+    case PC_ERR_FILE_OPERATION: return SECURITY_SERVER_API_ERROR_UNKNOWN;
+    case PC_ERR_MEM_OPERATION:  return SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
+    case PC_ERR_NOT_PERMITTED:  return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
+    case PC_ERR_INVALID_PARAM:  return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+    case PC_ERR_INVALID_OPERATION:
+    case PC_ERR_DB_OPERATION:
+    default:
+        ;
+    }
+    return SECURITY_SERVER_API_ERROR_UNKNOWN;
+}
+
+// interface ids
+const SecurityServer::InterfaceID CHANGE_APP_PERMISSIONS = 0;
+const SecurityServer::InterfaceID CHECK_APP_PRIVILEGE = 1;
+
+} // namespace anonymous
+
+namespace SecurityServer {
+
+GenericSocketService::ServiceDescriptionVector AppPermissionsService::GetServiceDescription() {
+    return ServiceDescriptionVector {
+        { SERVICE_SOCKET_APP_PERMISSIONS,
+          "security-server::api-app-permissions",
+          CHANGE_APP_PERMISSIONS },
+        { SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME,
+          "security-server::api-app-privilege-by-name",
+          CHECK_APP_PRIVILEGE }
+    };
+}
+
+void AppPermissionsService::accept(const AcceptEvent &event) {
+    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+    auto &info = m_connectionInfoMap[event.connectionID.counter];
+    info.interfaceID = event.interfaceID;
+}
+
+void AppPermissionsService::write(const WriteEvent &event) {
+    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+void AppPermissionsService::process(const ReadEvent &event) {
+    LogDebug("Read event for counter: " << event.connectionID.counter);
+    auto &info = m_connectionInfoMap[event.connectionID.counter];
+    info.buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, info.buffer, info.interfaceID));
+}
+
+void AppPermissionsService::close(const CloseEvent &event) {
+    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    m_connectionInfoMap.erase(event.connectionID.counter);
+}
+
+bool AppPermissionsService::processOne(const ConnectionID &conn,
+                                       MessageBuffer &buffer,
+                                       InterfaceID interfaceID)
+{
+    LogDebug("Iteration begin");
+
+    //waiting for all data
+    if (!buffer.Ready()) {
+        return false;
+    }
+
+    LogDebug("Entering app_permissions server side handler");
+
+    switch(interfaceID) {
+    case CHANGE_APP_PERMISSIONS:
+        return processPermissionsChange(conn, buffer);
+
+    case CHECK_APP_PRIVILEGE:
+        return processCheckAppPrivilege(conn, buffer);
+
+    default:
+        LogDebug("Unknown interfaceId. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+}
+
+bool AppPermissionsService::processPermissionsChange(const ConnectionID &conn, MessageBuffer &buffer)
+{
+    MessageBuffer send;
+    std::vector<std::string> permissions_list;
+    std::string app_id;
+    int persistent;
+    size_t iter;
+    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+    app_type_t app_type;
+    AppPermissionsAction appPermAction;
+
+    LogDebug("Processing permissions change request");
+
+    //receive data from buffer and check MSG_ID
+    Try {
+        int temp;
+        Deserialization::Deserialize(buffer, temp);                 //receive MSG_ID
+        appPermAction = (AppPermissionsAction)temp;
+
+        if (appPermAction == AppPermissionsAction::ENABLE)      //persistent is only in APP_ENABLE frame
+            Deserialization::Deserialize(buffer, persistent);
+
+        Deserialization::Deserialize(buffer, temp);
+        app_type = (app_type_t)temp;
+        Deserialization::Deserialize(buffer, app_id);
+        Deserialization::Deserialize(buffer, permissions_list);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    //+1 bellow is for NULL pointer at the end
+    std::unique_ptr<const char *[]> perm_list (new (std::nothrow) const char *[permissions_list.size() + 1]);
+    if (NULL == perm_list.get()) {
+        LogError("Allocation error");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    //print received data
+    LogDebug("app_type: " << (int)app_type);
+    if (appPermAction == AppPermissionsAction::ENABLE)    //persistent is only in APP_ENABLE frame
+        LogDebug("persistent: " << persistent);
+    LogDebug("app_id: " << app_id);
+
+    //left one free pointer for the NULL at the end
+    for (iter = 0; iter < permissions_list.size(); ++iter) {
+        LogDebug("perm_list[" << iter << "]: " << permissions_list[iter]);
+        perm_list[iter] = (permissions_list[iter]).c_str();
+    }
+    //put the NULL at the end
+    perm_list[iter] = NULL;
+
+    //use received data
+    if (appPermAction == AppPermissionsAction::ENABLE) {
+        LogDebug("Calling perm_app_enable_permissions()");
+        result = perm_app_enable_permissions(app_id.c_str(), app_type, perm_list.get(), persistent);
+        LogDebug("perm_app_enable_permissions() returned: " << result);
+    } else {
+        LogDebug("Calling perm_app_disable_permissions()");
+        result = perm_app_disable_permissions(app_id.c_str(), app_type, perm_list.get());
+        LogDebug("perm_app_disable_permissions() returned: " << result);
+    }
+
+    //send response
+    Serialization::Serialize(send, privilegeToSecurityServerError(result));
+    m_serviceManager->Write(conn, send.Pop());
+    return true;
+}
+
+bool AppPermissionsService::processCheckAppPrivilege(const ConnectionID &conn, MessageBuffer &buffer)
+{
+    MessageBuffer send;
+    std::string privilege_name;
+    std::string app_id;
+    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+    app_type_t app_type;
+    bool has_permission = false;
+    PrivilegeCheckHdrs checkType = PrivilegeCheckHdrs::CHECK_GIVEN_APP;
+
+    LogDebug("Processing app privilege check request");
+
+    //receive data from buffer
+    Try {
+        int temp;
+        Deserialization::Deserialize(buffer, temp); // call type
+        checkType = static_cast<PrivilegeCheckHdrs>(temp);
+        LogDebug("App privilege check call type: "
+                 << (checkType == PrivilegeCheckHdrs::CHECK_GIVEN_APP ?
+                     "CHECK_GIVEN_APP":"CHECK_CALLER_APP"));
+        if (checkType == PrivilegeCheckHdrs::CHECK_GIVEN_APP) { //app_id present only in this case
+            Deserialization::Deserialize(buffer, app_id); //get app id
+        }
+        Deserialization::Deserialize(buffer, temp); //get app type
+        app_type = static_cast<app_type_t>(temp);
+
+        Deserialization::Deserialize(buffer, privilege_name); //get privilege name
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    if (checkType == PrivilegeCheckHdrs::CHECK_CALLER_APP) { //get sender app_id in this case
+        char *label = NULL;
+        if (smack_new_label_from_socket(conn.sock, &label) < 0) {
+            LogDebug("Error in smack_new_label_from_socket(): "
+                     "client label is unknown. Sending error response.");
+            Serialization::Serialize(send, SECURITY_SERVER_API_ERROR_GETTING_SOCKET_LABEL_FAILED);
+            m_serviceManager->Write(conn, send.Pop());
+            return false;
+        } else {
+            app_id = label;
+            free(label);
+        }
+    } //end if
+
+    //print received data
+    LogDebug("app_id: " << app_id);
+    LogDebug("app_type: " << static_cast<int>(app_type));
+    LogDebug("privilege_name: " << privilege_name);
+
+    LogDebug("Calling perm_app_has_permission()");
+    result = perm_app_has_permission(app_id.c_str(), app_type, privilege_name.c_str(), &has_permission);
+    LogDebug("perm_app_has_permission() returned: " << result << " , permission enabled: " << has_permission);
+
+    //send response
+    Serialization::Serialize(send, privilegeToSecurityServerError(result));
+    Serialization::Serialize(send, static_cast<int>(has_permission));
+    m_serviceManager->Write(conn, send.Pop());
+    return true;
+}
+
+} // namespace SecurityServer
diff --git a/src/server/service/app-permissions.h b/src/server/service/app-permissions.h
new file mode 100644 (file)
index 0000000..166e7fe
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        app-permissions.h
+ * @author      Pawel Polawski (p.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This function contain header for implementation of security_server_app_enable_permissions
+ *              and SS_app_disable_permissions on server side
+ */
+
+#ifndef _SECURITY_SERVER_APP_PERMISSIONS_
+#define _SECURITY_SERVER_APP_PERMISSIONS_
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+#include <dpl/serialization.h>
+#include <message-buffer.h>
+#include <connection-info.h>
+
+namespace SecurityServer {
+
+class AppPermissionsService  :
+    public SecurityServer::GenericSocketService
+  , public SecurityServer::ServiceThread<AppPermissionsService>
+{
+public:
+    ServiceDescriptionVector GetServiceDescription();
+
+    DECLARE_THREAD_EVENT(AcceptEvent, accept)
+    DECLARE_THREAD_EVENT(WriteEvent, write)
+    DECLARE_THREAD_EVENT(ReadEvent, process)
+    DECLARE_THREAD_EVENT(CloseEvent, close)
+
+    void accept(const AcceptEvent &event);
+    void write(const WriteEvent &event);
+    void process(const ReadEvent &event);
+    void close(const CloseEvent &event);
+
+private:
+    bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
+
+    bool processPermissionsChange(const ConnectionID &conn, MessageBuffer &buffer);
+    bool processCheckAppPrivilege(const ConnectionID &conn, MessageBuffer &buffer);
+
+    ConnectionInfoMap m_connectionInfoMap;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_APP_ENABLE_PERMISSIONS_
diff --git a/src/server/service/cookie-jar.cpp b/src/server/service/cookie-jar.cpp
new file mode 100644 (file)
index 0000000..2e0e42b
--- /dev/null
@@ -0,0 +1,253 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        cookie-jar.cpp
+ * @author      Pawel Polawski (p.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This function contain implementation of CookieJar class which holds cookies structures
+ */
+
+#include <cookie-jar.h>
+#include <protocols.h>
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+#include <vector>
+#include <stdbool.h>
+#include <unistd.h>
+#include <smack-check.h>
+#include <privilege-control.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/smack.h>
+#include <fstream>
+#include <linux/limits.h>
+#include <signal.h>
+#include <errno.h>
+
+namespace SecurityServer {
+
+CookieJar::CookieJar(void)
+  : m_position(0)
+{
+    LogDebug("Created CookieJar for handling cookies");
+}
+
+CookieJar::~CookieJar(void)
+{
+    LogDebug("Deleted CookieJar");
+}
+
+const Cookie * CookieJar::GenerateCookie(int pid)
+{
+    char key[COOKIE_SIZE];
+    int retval;
+
+    LogDebug("Cookie creation called");
+
+    //create empty cookie class
+    Cookie newCookie;
+    newCookie.pid = pid;
+
+    //check if there is no cookie for specified PID
+    const Cookie *searchResult = SearchCookie(newCookie, CompareType::PID);
+    if (searchResult != NULL) {
+        LogDebug("Cookie exist for specified PID");
+        return searchResult;
+    }
+
+    searchResult = &newCookie;   //only for searchResult != NULL
+    while(searchResult != NULL) {
+        //generate unique key
+        std::ifstream urandom("/dev/urandom", std::ifstream::binary);
+        urandom.read(key, COOKIE_SIZE);
+        newCookie.cookieId.assign(key, key + COOKIE_SIZE);
+
+        //check if key is unique
+        searchResult = SearchCookie(newCookie, CompareType::COOKIE_ID);
+        if (searchResult != NULL)
+            LogDebug("Key is not unique");
+    }
+
+    //obtain process path
+    char link[PATH_MAX];
+    char path[PATH_MAX];
+
+    snprintf(link, PATH_MAX, "/proc/%d/exe", pid);
+    retval = readlink(link, path, PATH_MAX-1);
+    if (retval < 0) {
+        LogDebug("Unable to get process path");
+        return NULL;
+    }
+    path[retval] = '\0';
+    newCookie.binaryPath = path;
+
+    //get smack label if smack enabled
+    if (smack_check()) {
+        char label[SMACK_LABEL_LEN + 1];
+        retval = get_smack_label_from_process(pid, label);
+        if (retval != PC_OPERATION_SUCCESS) {
+            LogDebug("Unable to get smack label of process");
+            return NULL;
+        }
+        newCookie.smackLabel = label;
+    } else
+        newCookie.smackLabel = "";
+
+
+    //get GID list
+    const int NAME_SIZE = 64;
+    char filename[NAME_SIZE];
+
+    snprintf(filename, NAME_SIZE, "/proc/%d/status", pid);
+    std::ifstream status(filename, std::ifstream::binary);
+    std::string line;
+
+    while (std::getline(status, line)) {  //read line from file
+        const char *tmp = line.c_str();
+        if (strncmp(line.c_str(), "Uid:", 4) == 0)
+            newCookie.uid = atoi(&tmp[5]);
+        else if (strncmp(line.c_str(), "Gid:", 4) == 0)
+            newCookie.gid = atoi(&tmp[5]);
+        else if (strncmp(line.c_str(), "Groups:", 7) == 0) {
+            char delim[] = ": ";    //separators for strtok: ' ' and ':'
+            char *token = strtok(const_cast<char *>(tmp), delim);  //1st string is "Group:"
+            while ((token = strtok(NULL, delim))) {
+                int gid = atoi(token);
+                newCookie.permissions.push_back(gid);
+            }
+        }
+    }
+
+    //DEBUG ONLY
+    //print info about cookie
+    LogDebug("Cookie created");
+    LogDebug("PID: " << newCookie.pid);
+    LogDebug("UID: " << newCookie.uid);
+    LogDebug("GID: " << newCookie.gid);
+    LogDebug("PATH: " << newCookie.binaryPath);
+    LogDebug("LABEL: " << newCookie.smackLabel);
+    for (size_t k = 0; k < newCookie.permissions.size(); k++)
+        LogDebug("GID: " << newCookie.permissions[k]);
+
+    m_cookieList.push_back(newCookie);
+    return &m_cookieList[m_cookieList.size() - 1];
+}
+
+void CookieJar::DeleteCookie(const Cookie &pattern, CompareType criterion)
+{
+    if (m_cookieList.size() == 0) {
+        LogDebug("Cookie list empty");
+        return;
+    }
+
+    //for each cookie in list
+    for (size_t i = 0; i < m_cookieList.size();) {
+        if (CompareCookies(pattern, m_cookieList[i], criterion)) {
+            LogDebug("Deleting cookie");
+            if (i != m_cookieList.size() - 1)
+                m_cookieList[i] = *m_cookieList.rbegin();
+            m_cookieList.pop_back();
+        } else
+            ++i;
+    }
+}
+
+const Cookie * CookieJar::SearchCookie(const Cookie &pattern, CompareType criterion) const
+{
+    LogDebug("Searching for cookie");
+
+    if (m_cookieList.size() == 0) {
+        LogDebug("Cookie list empty");
+        return NULL;
+    }
+
+    //for each cookie in list
+    for (size_t i = 0; i < m_cookieList.size(); i++) {
+        if (CompareCookies(pattern, m_cookieList[i], criterion)) {
+            LogDebug("Cookie found");
+            return &(m_cookieList[i]);
+        }
+    }
+
+    LogDebug("Cookie not found");
+    return NULL;
+}
+
+bool CookieJar::CompareCookies(const Cookie &c1, const Cookie &c2, CompareType criterion) const
+{
+    size_t permSize1 = c1.permissions.size();
+    size_t permSize2 = c2.permissions.size();
+
+    switch(criterion) {
+    case CompareType::COOKIE_ID:
+        return (c1.cookieId == c2.cookieId);
+
+    case CompareType::PID:
+        return (c1.pid == c2.pid);
+
+    case CompareType::PATH:
+        return (c1.binaryPath == c2.binaryPath);
+
+    case CompareType::SMACKLABEL:
+        return (c1.smackLabel == c2.smackLabel);
+
+    case CompareType::PERMISSIONS:
+        //we search for at least one the same GID
+        for(size_t i = 0; i < permSize1; i++)
+            for (size_t k = 0; k < permSize2; k++)
+                if (c1.permissions[i] == c2.permissions[k])
+                    return true;
+        return false;
+
+    case CompareType::UID:
+        return (c1.uid == c2.uid);
+
+    case CompareType::GID:
+        return (c1.gid == c2.gid);
+
+    default:
+        LogDebug("Wrong function parameters");
+        return false;
+    };
+}
+
+void CookieJar::GarbageCollector(size_t howMany)
+{
+    if ((howMany == 0) || (howMany > m_cookieList.size())) {
+        howMany = m_cookieList.size();
+    }
+
+    for (size_t i = 0; i < howMany; ++i) {
+
+        if (m_position >= m_cookieList.size()) {
+            m_position = 0;
+        }
+
+        if (kill(m_cookieList[m_position].pid, 0) && (errno == ESRCH)) {
+            LogDebug("Cookie deleted " << " PID:" << m_cookieList[m_position].pid);
+            if (m_position != (m_cookieList.size()-1))
+                m_cookieList[m_position] = *m_cookieList.rbegin();
+            m_cookieList.pop_back();
+        } else {
+            ++m_position;
+        }
+    }
+}
+
+} // namespace SecurityServer
diff --git a/src/server/service/cookie-jar.h b/src/server/service/cookie-jar.h
new file mode 100644 (file)
index 0000000..1f81c7a
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        cookie-jar.h
+ * @author      Pawel Polawski (p.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This function contain header of CookieJar class which holds cookies structures
+ */
+
+#ifndef _SECURITY_SERVER_COOKIE_JAR_
+#define _SECURITY_SERVER_COOKIE_JAR_
+
+#include <stdio.h>
+
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+#include <vector>
+#include <stdbool.h>
+
+
+namespace SecurityServer {
+
+enum class CompareType
+{
+    COOKIE_ID,
+    PID,
+    PATH,
+    SMACKLABEL,
+    PERMISSIONS,
+    UID,
+    GID
+};
+
+
+struct Cookie
+{
+    std::vector<char> cookieId;     //ID key
+    pid_t pid;                      //owner PID
+    uid_t uid;                      //owner UID
+    gid_t gid;                      //owner GID
+    std::string binaryPath;         //path to owner binary
+    std::string smackLabel;         //owner SMACK label
+    std::vector<int> permissions;   //owner GIDs
+};
+
+
+class CookieJar
+{
+public:
+    CookieJar(void);
+    virtual ~CookieJar(void);
+
+    const Cookie * GenerateCookie(int pid);
+    void DeleteCookie(const Cookie &pattern, CompareType criterion);
+
+    const Cookie * SearchCookie(const Cookie &pattern, CompareType criterion) const;
+    bool CompareCookies(const Cookie &c1, const Cookie &c2, CompareType criterion) const;
+
+    // howMany - number of cookies that will be checked.
+    // Set howMay to 0 to check all cookies.
+    void GarbageCollector(size_t howMany);
+
+private:
+    size_t m_position;
+    std::vector<Cookie> m_cookieList;
+};
+
+
+} // namespace SecurityServer
+#endif // _SECURITY_SERVER_COOKIE_JAR_
diff --git a/src/server/service/cookie.cpp b/src/server/service/cookie.cpp
new file mode 100644 (file)
index 0000000..a7a8c92
--- /dev/null
@@ -0,0 +1,388 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        cookie.cpp
+ * @author      Pawel Polawski (p.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This function contain implementation of CookieService
+ */
+
+#include <memory>
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+#include <protocols.h>
+#include <security-server.h>
+#include <cookie.h>
+#include <smack-check.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/smack.h>
+
+//interfaces ID
+const int INTERFACE_GET = 0;
+const int INTERFACE_CHECK = 1;
+const int INTERFACE_CHECK_TMP = 3;
+
+namespace SecurityServer {
+
+GenericSocketService::ServiceDescriptionVector CookieService::GetServiceDescription() {
+    return ServiceDescriptionVector {
+        {SERVICE_SOCKET_COOKIE_GET,       "security-server::api-cookie-get",   INTERFACE_GET },
+        {SERVICE_SOCKET_COOKIE_CHECK,     "security-server::api-cookie-check", INTERFACE_CHECK},
+        {SERVICE_SOCKET_COOKIE_CHECK_TMP, "security-server::api-cookie-check", INTERFACE_CHECK_TMP}
+    };
+ }
+
+void CookieService::accept(const AcceptEvent &event) {
+    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+    auto &info = m_connectionInfoMap[event.connectionID.counter];
+    info.interfaceID = event.interfaceID;
+}
+
+void CookieService::write(const WriteEvent &event) {
+    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+void CookieService::process(const ReadEvent &event) {
+    LogDebug("Read event for counter: " << event.connectionID.counter);
+    auto &info = m_connectionInfoMap[event.connectionID.counter];
+    info.buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, info.buffer, info.interfaceID));
+}
+
+void CookieService::close(const CloseEvent &event) {
+    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    m_connectionInfoMap.erase(event.connectionID.counter);
+}
+
+bool CookieService::processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID)
+{
+    LogDebug("Iteration begin");
+    MessageBuffer send, recv;
+    CookieCall msgType;
+    bool removeGarbage = false;
+
+    //waiting for all data
+    if (!buffer.Ready()) {
+        return false;
+    }
+
+    //receive data from buffer and check MSG_ID
+    Try {
+        int msgTypeInt;
+        Deserialization::Deserialize(buffer, msgTypeInt);  //receive MSG_ID
+        msgType = static_cast<CookieCall>(msgTypeInt);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    bool retval = false;
+
+    //use received data
+    if (interfaceID == INTERFACE_GET) {
+        switch(msgType) {
+        case CookieCall::GET_COOKIE:
+            LogDebug("Entering get-cookie server side handler");
+            retval = cookieRequest(send, conn.sock);
+            removeGarbage = true;
+            break;
+
+        default:
+            LogDebug("Error, unknown function called by client");
+            retval = false;
+            break;
+        };
+    } else if (interfaceID == INTERFACE_CHECK) {
+        switch(msgType) {
+        case CookieCall::CHECK_PID:
+            LogDebug("Entering pid-by-cookie server side handler");
+            retval = pidByCookieRequest(buffer, send);
+            break;
+
+        case CookieCall::CHECK_SMACKLABEL:
+            LogDebug("Entering smacklabel-by-cookie server side handler");
+            retval = smackLabelByCookieRequest(buffer, send);
+            break;
+
+        case CookieCall::CHECK_PRIVILEGE_GID:
+            LogDebug("Entering check-privilege-by-cookie-gid server side handler");
+            retval = privilegeByCookieGidRequest(buffer, send);
+            break;
+
+        case CookieCall::CHECK_PRIVILEGE:
+            LogDebug("Entering check-privilege-by-cookie side handler");
+            retval = privilegeByCookieRequest(buffer, send);
+            break;
+
+        default:
+            LogDebug("Error, unknown function called by client");
+            retval = false;
+            break;
+        };
+    } else if (interfaceID == INTERFACE_CHECK_TMP) {
+        //TODO: Merge this interface with INTERFACE_CHECK after INTERFACE_CHECK will be secured by smack 
+        switch(msgType) {
+        case CookieCall::CHECK_UID:
+            LogDebug("Entering get-uid-by-cookie side handler");
+            retval = uidByCookieRequest(buffer, send);
+            break;
+
+        case CookieCall::CHECK_GID:
+            LogDebug("Entering get-gid-by-cookie side handler");
+            retval = gidByCookieRequest(buffer, send);
+            break;
+
+        default:
+            LogDebug("Error, unknown function called by client");
+            retval = false;
+            break;
+        };
+    } else {
+        LogDebug("Error, wrong interface");
+        retval = false;
+    }
+
+    if (retval) {
+        //send response
+        m_serviceManager->Write(conn, send.Pop());
+    } else {
+        LogDebug("Closing socket because of error");
+        m_serviceManager->Close(conn);
+    }
+
+    // Each time you add one cookie check 2 others.
+    if (removeGarbage)
+        m_cookieJar.GarbageCollector(2);
+
+    return retval;
+}
+
+bool CookieService::cookieRequest(MessageBuffer &send, int socket)
+{
+    struct ucred cr;
+    unsigned len = sizeof(cr);
+
+    if (0 != getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &cr, &len))
+        return false;
+
+    const Cookie *generatedCookie = m_cookieJar.GenerateCookie(cr.pid);
+    if (generatedCookie != NULL) {
+        //cookie created correct
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+        Serialization::Serialize(send, generatedCookie->cookieId);
+    } else {
+        //unable to create cookie
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_UNKNOWN);
+    }
+
+    return true;
+}
+
+bool CookieService::pidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
+{
+    std::vector<char> cookieKey;
+
+    Try {
+        Deserialization::Deserialize(buffer, cookieKey);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        return false;
+    }
+
+    Cookie searchPattern;
+    searchPattern.cookieId = cookieKey;
+
+    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
+
+    if (searchResult != NULL) {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+        Serialization::Serialize(send, (int)searchResult->pid);
+    } else {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
+    }
+
+    return true;
+}
+
+bool CookieService::smackLabelByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
+{
+    std::vector<char> cookieKey;
+
+    Try {
+        Deserialization::Deserialize(buffer, cookieKey);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        return false;
+    }
+
+    Cookie searchPattern;
+    searchPattern.cookieId = cookieKey;
+
+    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
+
+    if (searchResult != NULL) {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+        Serialization::Serialize(send, searchResult->smackLabel);
+    } else {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
+    }
+
+    return true;
+}
+
+bool CookieService::privilegeByCookieGidRequest(MessageBuffer &buffer, MessageBuffer &send)
+{
+    std::vector<char> cookieKey;
+    int gid;
+
+    Try {
+        Deserialization::Deserialize(buffer, cookieKey);
+        Deserialization::Deserialize(buffer, gid);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        return false;
+    }
+
+    Cookie searchPattern;
+    searchPattern.cookieId = cookieKey;
+
+    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
+
+    if (searchResult != NULL)
+        //search for specified GID on permissions list
+        for (size_t i = 0; i < searchResult->permissions.size(); i++)
+            if (searchResult->permissions[i] == gid) {
+                Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+                return true;
+            }
+
+    Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_ACCESS_DENIED);
+
+    return true;
+}
+
+bool CookieService::privilegeByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
+{
+    std::vector<char> cookieKey;
+    std::string subject;
+    std::string object;
+    std::string access;
+
+    Try {
+        Deserialization::Deserialize(buffer, cookieKey);
+        Deserialization::Deserialize(buffer, object);
+        Deserialization::Deserialize(buffer, access);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        return false;
+    }
+
+    Cookie searchPattern;
+    searchPattern.cookieId = cookieKey;
+
+    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
+
+    if (searchResult != NULL) {
+        if (!smack_check()) {
+            Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+        } else {
+            subject = searchResult->smackLabel;
+            int retval;
+
+            if ((retval = smack_have_access(subject.c_str(), object.c_str(), access.c_str())) == 1)
+                Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+            else {
+                Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_ACCESS_DENIED);
+                LogSmackAudit("SS_SMACK: "
+                    << " subject=" << subject
+                    << ", object=" << object
+                    << ", access=" << access
+                    << ", result=" << retval);
+            }
+        }
+    } else {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
+    }
+
+    return true;
+}
+
+bool CookieService::uidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
+{
+    std::vector<char> cookieKey;
+
+    Try {
+        Deserialization::Deserialize(buffer, cookieKey);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        return false;
+    }
+
+    Cookie searchPattern;
+    searchPattern.cookieId = cookieKey;
+
+    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
+
+    if (searchResult != NULL) {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+        Serialization::Serialize(send, (int)searchResult->uid);
+    } else {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
+    }
+
+    return true;
+}
+
+bool CookieService::gidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
+{
+    std::vector<char> cookieKey;
+
+    Try {
+        Deserialization::Deserialize(buffer, cookieKey);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        return false;
+    }
+
+    Cookie searchPattern;
+    searchPattern.cookieId = cookieKey;
+
+    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
+
+    if (searchResult != NULL) {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
+        Serialization::Serialize(send, (int)searchResult->gid);
+    } else {
+        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
+    }
+
+    return true;
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/service/cookie.h b/src/server/service/cookie.h
new file mode 100644 (file)
index 0000000..2a2a922
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        cookie.h
+ * @author      Pawel Polawski (p.polawski@partner.samsung.com)
+ * @version     1.0
+ * @brief       This function contain header for implementation of cookie get API
+ */
+
+#ifndef _SECURITY_SERVER_COOKIE_GET_
+#define _SECURITY_SERVER_COOKIE_GET_
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+#include <dpl/serialization.h>
+#include <message-buffer.h>
+#include <connection-info.h>
+#include <cookie-jar.h>
+
+namespace SecurityServer {
+
+class CookieService  :
+    public SecurityServer::GenericSocketService
+  , public SecurityServer::ServiceThread<CookieService>
+{
+public:
+
+    ServiceDescriptionVector GetServiceDescription();
+
+    DECLARE_THREAD_EVENT(AcceptEvent, accept)
+    DECLARE_THREAD_EVENT(WriteEvent, write)
+    DECLARE_THREAD_EVENT(ReadEvent, process)
+    DECLARE_THREAD_EVENT(CloseEvent, close)
+
+    void accept(const AcceptEvent &event);
+    void write(const WriteEvent &event);
+    void process(const ReadEvent &event);
+    void close(const CloseEvent &event);
+
+private:
+    bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
+
+    bool cookieRequest(MessageBuffer &send, int socket);
+
+    bool pidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
+    bool smackLabelByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
+    bool privilegeByCookieGidRequest(MessageBuffer &buffer, MessageBuffer &send);
+    bool privilegeByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
+
+    bool uidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
+    bool gidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
+
+    CookieJar m_cookieJar;
+
+    ConnectionInfoMap m_connectionInfoMap;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_APP_ENABLE_PERMISSIONS_
diff --git a/src/server/service/data-share.cpp b/src/server/service/data-share.cpp
new file mode 100644 (file)
index 0000000..0c64a60
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        data-share.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of api-data-share service.
+ */
+
+#include <sys/smack.h>
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+
+#include <protocols.h>
+#include <data-share.h>
+#include <security-server.h>
+#include <security-server-util.h>
+#include <smack-check.h>
+
+namespace SecurityServer {
+
+GenericSocketService::ServiceDescriptionVector SharedMemoryService::GetServiceDescription() {
+    return ServiceDescriptionVector
+        {{SERVICE_SOCKET_SHARED_MEMORY, "security-server::api-data-share"}};
+}
+
+void SharedMemoryService::accept(const AcceptEvent &event) {
+    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+}
+
+void SharedMemoryService::write(const WriteEvent &event) {
+    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+bool SharedMemoryService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
+    LogDebug("Iteration begin");
+    static const char * const revoke = "-----";
+    static const char * const permissions = "rwxat";
+    char *providerLabel = NULL;
+    std::string clientLabel;
+    int clientPid = 0;
+    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+    struct smack_accesses *smack = NULL;
+
+    if (!buffer.Ready()) {
+        return false;
+    }
+
+    Try {
+        Deserialization::Deserialize(buffer, clientLabel);
+        Deserialization::Deserialize(buffer, clientPid);
+     } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    if (smack_check()) {
+        if (0 != smack_new_label_from_socket(conn.sock, &providerLabel)) {
+            LogDebug("Error in smack_new_label_from_socket");
+            retCode = SECURITY_SERVER_API_ERROR_BAD_REQUEST;
+            goto end;
+        }
+
+        if (!util_smack_label_is_valid(clientLabel.c_str())) {
+            LogDebug("Invalid smack label: " << clientLabel);
+            retCode = SECURITY_SERVER_API_ERROR_BAD_REQUEST;
+            goto end;
+        }
+
+        if (smack_accesses_new(&smack)) {
+            LogDebug("Error in smack_accesses_new");
+            goto end;
+        }
+
+        if (smack_accesses_add_modify(smack, clientLabel.c_str(), providerLabel,
+              permissions, revoke))
+        {
+            LogDebug("Error in smack_accesses_add_modify");
+            goto end;
+        }
+
+        if (smack_accesses_apply(smack)) {
+            LogDebug("Error in smack_accesses_apply");
+            retCode = SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
+            goto end;
+        }
+        LogDebug("Access granted. Subject: " << clientLabel << " Provider: " << providerLabel);
+    }
+    retCode = SECURITY_SERVER_API_SUCCESS;
+end:
+    free(providerLabel);
+    smack_accesses_free(smack);
+
+    MessageBuffer sendBuffer;
+    Serialization::Serialize(sendBuffer, retCode);
+    m_serviceManager->Write(conn, sendBuffer.Pop());
+    return true;
+}
+
+void SharedMemoryService::process(const ReadEvent &event) {
+    LogDebug("Read event for counter: " << event.connectionID.counter);
+    auto &buffer = m_messageBufferMap[event.connectionID.counter];
+    buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, buffer));
+}
+
+void SharedMemoryService::close(const CloseEvent &event) {
+    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    m_messageBufferMap.erase(event.connectionID.counter);
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/service/data-share.h b/src/server/service/data-share.h
new file mode 100644 (file)
index 0000000..1626c32
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        data-share.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of api-data-share
+ */
+
+#ifndef _SECURITY_SERVER_DATA_SHARE_
+#define _SECURITY_SERVER_DATA_SHARE_
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+
+#include <message-buffer.h>
+
+namespace SecurityServer {
+
+class SharedMemoryService
+  : public SecurityServer::GenericSocketService
+  , public SecurityServer::ServiceThread<SharedMemoryService>
+{
+public:
+    typedef std::map<int, MessageBuffer> MessageBufferMap;
+
+    ServiceDescriptionVector GetServiceDescription();
+
+    DECLARE_THREAD_EVENT(AcceptEvent, accept)
+    DECLARE_THREAD_EVENT(WriteEvent, write)
+    DECLARE_THREAD_EVENT(ReadEvent, process)
+    DECLARE_THREAD_EVENT(CloseEvent, close)
+
+    void accept(const AcceptEvent &event);
+    void write(const WriteEvent &event);
+    void process(const ReadEvent &event);
+    void close(const CloseEvent &event);
+private:
+    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
+
+    MessageBufferMap m_messageBufferMap;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_DATA_SHARE_
diff --git a/src/server/service/get-gid.cpp b/src/server/service/get-gid.cpp
new file mode 100644 (file)
index 0000000..86ca202
--- /dev/null
@@ -0,0 +1,158 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        get-gid.cpp
+ * @author      Jan Olszak (j.olszak@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of api-get-gid service.
+ */
+
+#include <unistd.h>
+#include <sys/smack.h>
+#include <grp.h>
+#include <unistd.h>
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+
+#include <protocols.h>
+#include <get-gid.h>
+#include <security-server.h>
+
+namespace SecurityServer {
+
+GenericSocketService::ServiceDescriptionVector GetGidService::GetServiceDescription() {
+    return ServiceDescriptionVector
+        {{SERVICE_SOCKET_GET_GID, "*"}};
+}
+
+void GetGidService::accept(const AcceptEvent &event) {
+    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+}
+
+void GetGidService::write(const WriteEvent &event) {
+    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+
+/*
+ * Searches for group ID by given group name
+ */
+int GetGidService::setGid(std::string& obj)
+{
+    int ret = 0;
+    struct group *grpbuf = NULL;
+    struct group grp;
+    std::vector<char> buf;
+
+    /*
+     * The maximum needed size for buf can be found using sysconf(3)
+     * with the argument _SC_GETGR_R_SIZE_MAX. If _SC_GETGR_R_SIZE_MAX is not
+     * returned we set max_buf_size to 1024 bytes. Enough to store few groups.
+     */
+    long int maxBufSize = sysconf(_SC_GETGR_R_SIZE_MAX);
+    if (maxBufSize == -1)
+        maxBufSize = 1024;
+
+
+    /*
+     * There can be some corner cases when for example user is assigned to a
+     * lot of groups. In that case if buffer is to small getgrnam_r will
+     * return ERANGE error. Solution could be calling getgrnam_r with bigger
+     * buffer until it's big enough.
+     */
+    do {
+        try{
+            buf.resize(maxBufSize);
+        }catch(std::bad_alloc&) {
+            ret = SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
+            LogError("Out Of Memory");
+            return ret;
+        }
+        maxBufSize *= 2;
+    } while ((ret = getgrnam_r(obj.c_str(), &grp, &(buf[0]), buf.size(), &grpbuf)) == ERANGE);
+
+    // Check for errors:
+    if (ret != 0){
+        ret = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+        LogError("getgrnam_r failed with error: " << strerror(errno));
+        return ret;
+
+    } else if (grpbuf == NULL) {
+        ret = SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT;
+        LogError("Cannot find gid for group: " << obj);
+        return ret;
+    }
+
+    m_gid = grpbuf->gr_gid;
+
+    return ret;
+}
+
+
+bool GetGidService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
+    LogDebug("Iteration begin");
+    std::string objectName;
+    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+    if (!buffer.Ready()) {
+        return false;
+    }
+
+    // Get objects name:
+    Try {
+        Deserialization::Deserialize(buffer, objectName);
+     } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    // Get GID
+    retCode = setGid(objectName);
+
+    // Send the result
+    MessageBuffer sendBuffer;
+    Serialization::Serialize(sendBuffer, retCode);
+    Serialization::Serialize(sendBuffer, m_gid);
+    m_serviceManager->Write(conn, sendBuffer.Pop());
+    return true;
+}
+
+void GetGidService::process(const ReadEvent &event) {
+    LogDebug("Read event for counter: " << event.connectionID.counter);
+    auto &buffer = m_messageBufferMap[event.connectionID.counter];
+    buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, buffer));
+}
+
+void GetGidService::close(const CloseEvent &event) {
+    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    m_messageBufferMap.erase(event.connectionID.counter);
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/service/get-gid.h b/src/server/service/get-gid.h
new file mode 100644 (file)
index 0000000..ac87081
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        get-gid.h
+ * @author      Jan Olszak (j.olszak@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of api-get-gid
+ */
+
+#ifndef _SECURITY_SERVER_GET_GID_
+#define _SECURITY_SERVER_GET_GID_
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+
+#include <dpl/serialization.h>
+#include <message-buffer.h>
+
+namespace SecurityServer {
+
+class GetGidService  : 
+    public SecurityServer::GenericSocketService
+  , public SecurityServer::ServiceThread<GetGidService>
+{
+public:
+    typedef std::map<int, MessageBuffer> MessageBufferMap;
+
+    ServiceDescriptionVector GetServiceDescription();
+
+    DECLARE_THREAD_EVENT(AcceptEvent, accept)
+    DECLARE_THREAD_EVENT(WriteEvent, write)
+    DECLARE_THREAD_EVENT(ReadEvent, process)
+    DECLARE_THREAD_EVENT(CloseEvent, close)
+
+    void accept(const AcceptEvent &event);
+    void write(const WriteEvent &event);
+    void process(const ReadEvent &event);
+    void close(const CloseEvent &event);
+private:
+    gid_t m_gid;
+    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
+    int  setGid(std::string& objectName);
+    MessageBufferMap m_messageBufferMap;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_GET_GID_
diff --git a/src/server/service/get-object-name.cpp b/src/server/service/get-object-name.cpp
new file mode 100644 (file)
index 0000000..b3491a9
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        get-object-name.cpp
+ * @author      Jan Olszak (j.olszak@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of api-get-object-name service.
+ */
+
+#include <sys/smack.h>
+#include <grp.h>
+#include <unistd.h>
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+
+#include <protocols.h>
+#include <get-object-name.h>
+#include <security-server.h>
+
+#include <vector>
+
+namespace SecurityServer {
+
+GetObjectNameService::ServiceDescriptionVector GetObjectNameService::GetServiceDescription() {
+    return ServiceDescriptionVector
+        {{SERVICE_SOCKET_GET_OBJECT_NAME, "*"}};
+}
+
+void GetObjectNameService::accept(const AcceptEvent &event) {
+    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+}
+
+void GetObjectNameService::write(const WriteEvent &event) {
+    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+
+
+/*
+ * Searches for group NAME by given group id
+ */
+int GetObjectNameService::setName(const gid_t gid)
+{
+    int ret = 0;
+    struct group *grpbuf = NULL;
+    struct group grp;
+    std::vector<char> buf;
+
+    /*
+     * The maximum needed size for buf can be found using sysconf(3)
+     * with the argument _SC_GETGR_R_SIZE_MAX. If _SC_GETGR_R_SIZE_MAX is not
+     * returned we set max_buf_size to 1024 bytes. Enough to store few groups.
+     */
+    long int maxBufSize = sysconf(_SC_GETGR_R_SIZE_MAX);
+    if (maxBufSize == -1)
+        maxBufSize = 1024;
+
+
+    /*
+     * There can be some corner cases when for example user is assigned to a
+     * lot of groups. In that case if buffer is to small getgrnam_r will
+     * return ERANGE error. Solution could be calling getgrnam_r with bigger
+     * buffer until it's big enough.
+     */
+    do {
+        try{
+            buf.resize(maxBufSize);
+        }catch(std::bad_alloc&) {
+            ret = SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
+            LogError("Out Of Memory");
+            return ret;
+        }
+        maxBufSize *= 2;
+
+    } while ((ret = getgrgid_r(gid, &grp, &(buf[0]), buf.size(), &grpbuf)) == ERANGE);
+
+    // Check for errors:
+    if (ret != 0){
+        ret = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+        LogError("getgrgid_r failed with error: " << strerror(errno));
+        return ret;
+
+    } else if (grpbuf == NULL) {
+        ret = SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT;
+        LogError("Cannot find name for group: " << gid);
+        return ret;
+    }
+
+    m_name = grpbuf->gr_name;
+
+    return ret;
+}
+
+
+bool GetObjectNameService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
+    LogDebug("Iteration begin");
+    gid_t gid;
+    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+    if (!buffer.Ready()) {
+        return false;
+    }
+
+    // Get objects GID:
+    Try {
+        Deserialization::Deserialize(buffer, gid);
+     } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    // Get name
+    retCode = setName(gid);
+
+    // Send the result
+    MessageBuffer sendBuffer;
+    Serialization::Serialize(sendBuffer, retCode);
+    Serialization::Serialize(sendBuffer, m_name);
+    m_serviceManager->Write(conn, sendBuffer.Pop());
+    return true;
+}
+
+void GetObjectNameService::process(const ReadEvent &event) {
+    LogDebug("Read event for counter: " << event.connectionID.counter);
+    auto &buffer = m_messageBufferMap[event.connectionID.counter];
+    buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, buffer));
+}
+
+void GetObjectNameService::close(const CloseEvent &event) {
+    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    m_messageBufferMap.erase(event.connectionID.counter);
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/service/get-object-name.h b/src/server/service/get-object-name.h
new file mode 100644 (file)
index 0000000..6950b55
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        get-object-name.h
+ * @author      Jan Olszak (j.olszak@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of api-get-object-name service.
+ */
+
+#ifndef _SECURITY_SERVER_SERV_GET_OBJECT_NAME_
+#define _SECURITY_SERVER_SERV_GET_OBJECT_NAME_
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+
+#include <dpl/serialization.h>
+#include <message-buffer.h>
+
+namespace SecurityServer {
+
+class GetObjectNameService  :
+    public SecurityServer::GenericSocketService
+  , public SecurityServer::ServiceThread<GetObjectNameService>
+{
+public:
+    typedef std::map<int, MessageBuffer> MessageBufferMap;
+
+    ServiceDescriptionVector GetServiceDescription();
+
+    DECLARE_THREAD_EVENT(AcceptEvent, accept)
+    DECLARE_THREAD_EVENT(WriteEvent, write)
+    DECLARE_THREAD_EVENT(ReadEvent, process)
+    DECLARE_THREAD_EVENT(CloseEvent, close)
+
+    void accept(const AcceptEvent &event);
+    void write(const WriteEvent &event);
+    void process(const ReadEvent &event);
+    void close(const CloseEvent &event);
+
+private:
+    std::string m_name;
+    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
+    int  setName(gid_t gid);
+    MessageBufferMap m_messageBufferMap;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_SERV_GET_OBJECT_NAME_
diff --git a/src/server/service/open-for-manager.cpp b/src/server/service/open-for-manager.cpp
new file mode 100644 (file)
index 0000000..e1570dd
--- /dev/null
@@ -0,0 +1,249 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        open-for-manager.cpp
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of open-for management functions
+ */
+
+#include "open-for-manager.h"
+
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <dirent.h>
+#include <fcntl.h>
+
+#include <sys/smack.h>
+#include <smack-check.h>
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+
+#include <security-server.h>
+#include <security-server-util.h>
+
+const std::string DATA_DIR = "/var/run/security-server";
+const std::string PROHIBITED_STR = "..";
+const std::string ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ \
+                                   abcdefghijklmnopqrstuvwxyz \
+                                   0123456789._-";
+
+namespace SecurityServer
+{
+    // SockCred implementations
+    SockCred::SockCred()
+    {
+        m_len = sizeof(struct ucred);
+        memset(&m_cr, 0, m_len);
+    }
+
+    bool SockCred::getCred(int socket)
+    {
+        if (getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &m_cr, &m_len)) {
+            int err = errno;
+            LogError("Unable to get client credentials: " << strerror(err));
+            return true;
+        }
+
+        if (smack_check()) {
+            char label[SMACK_LABEL_LEN + 1];
+            if (PC_OPERATION_SUCCESS != get_smack_label_from_process(m_cr.pid, label)) {
+                LogError("Unable to get smack label of process.");
+                return true;
+            }
+            m_sockSmackLabel = label;
+        } else
+            m_sockSmackLabel = "";
+
+        return false;
+    }
+
+    std::string SockCred::getLabel() const
+    {
+        return m_sockSmackLabel;
+    }
+
+    // SharedFile implementations
+    SharedFile::SharedFile()
+    {
+        if (!dirExist(DATA_DIR.c_str()))
+            mkdir(DATA_DIR.c_str(), 0700);
+        else {
+            deleteDir(DATA_DIR.c_str());
+            mkdir(DATA_DIR.c_str(), 0700);
+        }
+    }
+
+    bool SharedFile::fileExist(const std::string &filename) const
+    {
+        std::string filepath = DATA_DIR + "/" + filename;
+        struct stat buf;
+
+        return ((lstat(filepath.c_str(), &buf) == 0) &&
+                (((buf.st_mode) & S_IFMT) != S_IFLNK));
+    }
+
+    bool SharedFile::dirExist(const std::string &dirpath) const
+    {
+        struct stat buf;
+
+        return ((lstat(dirpath.c_str(), &buf) == 0) &&
+                (((buf.st_mode) & S_IFMT) == S_IFDIR));
+    }
+
+    bool SharedFile::deleteDir(const std::string &dirpath) const
+    {
+        DIR *dirp;
+        struct dirent *dp;
+        char path[PATH_MAX];
+
+        if ((dirp = opendir(dirpath.c_str())) == NULL) {
+            int err = errno;
+            LogError("Cannot open data directory. " << strerror(err));
+            return true;
+        }
+
+        while ((dp = readdir(dirp)) != NULL) {
+            if (strcmp(dp->d_name, ".") && strcmp(dp->d_name, "..")) {
+                snprintf(path, (size_t) PATH_MAX, "%s/%s", dirpath.c_str(), dp->d_name);
+                if (dp->d_type == DT_DIR) {
+                    deleteDir(path);
+                } else {
+                    unlink(path);
+                }
+            }
+        }
+        closedir(dirp);
+        rmdir(dirpath.c_str());
+
+        return false;
+    }
+
+    bool SharedFile::createFile(const std::string &filename)
+    {
+        int fd = -1;
+        std::string filepath = DATA_DIR + "/" + filename;
+
+        fd = TEMP_FAILURE_RETRY(open(filepath.c_str(), O_CREAT | O_WRONLY | O_EXCL, 0600));
+        int err = errno;
+        if (-1 == fd) {
+            LogError("Cannot create file. Error in open(): " << strerror(err));
+            return true;
+        }
+
+        TEMP_FAILURE_RETRY(close(fd));
+
+        return false;
+    }
+
+    int SharedFile::openFile(const std::string &filename)
+    {
+        int fd = -1;
+        std::string filepath = DATA_DIR + "/" + filename;
+
+        fd = TEMP_FAILURE_RETRY(open(filepath.c_str(), O_CREAT | O_RDWR, 0600));
+        int err = errno;
+        if (-1 == fd) {
+            LogError("Cannot open file. Error in open(): " << strerror(err));
+            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+        }
+
+        return fd;
+    }
+
+    bool SharedFile::setFileLabel(const std::string &filename, const std::string &label) const
+    {
+        std::string filepath = DATA_DIR + "/" + filename;
+
+        if (smack_setlabel(filepath.c_str(), label.c_str(), SMACK_LABEL_ACCESS)) {
+            LogError("Cannot set SMACK label on file.");
+            return true;
+        }
+
+        return false;
+    }
+
+    bool SharedFile::getFileLabel(const std::string &filename)
+    {
+        std::string filepath = DATA_DIR + "/" + filename;
+
+        if (smack_check()) {
+            char *label = NULL;
+            if (PC_OPERATION_SUCCESS != smack_getlabel(filepath.c_str(), &label, SMACK_LABEL_ACCESS)) {
+                LogError("Unable to get smack label of process.");
+                return true;
+            }
+            m_fileSmackLabel = label;
+            free(label);
+        } else
+            m_fileSmackLabel.clear();
+
+        return false;
+    }
+
+    bool SharedFile::checkFileNameSyntax(const std::string &filename) const
+    {
+        std::size_t found = filename.find_first_not_of(ALLOWED_CHARS);
+
+        if (found != std::string::npos || '-' == filename[0] ||
+            '.' == filename[0]) {
+            LogError("Illegal character in filename.");
+            return true;
+        }
+
+        found = filename.find(PROHIBITED_STR);
+        if (found != std::string::npos) {
+            LogError("Illegal string in filename.");
+            return true;
+        }
+
+        return false;
+    }
+
+    int SharedFile::getFD(const std::string &filename, int socket, int &fd)
+    {
+        if (checkFileNameSyntax(filename))
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+        if (m_sockCred.getCred(socket))
+            return SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED;
+
+        if (!fileExist(filename)) {
+            LogSecureDebug("File: " << filename.c_str() << " does not exist.");
+
+            if (createFile(filename))
+                return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+        }
+
+        if (getFileLabel(filename))
+            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+        if (setFileLabel(filename, m_sockCred.getLabel()))
+            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+        fd = openFile(filename);
+
+        if (setFileLabel(filename, m_fileSmackLabel))
+            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+} //namespace SecurityServer
diff --git a/src/server/service/open-for-manager.h b/src/server/service/open-for-manager.h
new file mode 100644 (file)
index 0000000..7e67002
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        open-for-manager.h
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of open-for management functions
+ */
+
+#ifndef _OPEN_FOR_MANAGER_H_
+#define _OPEN_FOR_MANAGER_H_
+
+#include <sys/socket.h>
+#include <sys/types.h>
+
+#include <string>
+
+namespace SecurityServer
+{
+    // classess
+    class SockCred
+    {
+    public:
+        SockCred();
+        bool getCred(int socket);
+        std::string getLabel(void) const;
+
+    private:
+        struct ucred m_cr;
+        unsigned m_len;
+        std::string m_sockSmackLabel;
+    };
+
+    class SharedFile
+    {
+    public:
+        SharedFile();
+        int getFD(const std::string &filename, int socket, int &fd);
+
+    private:
+        bool fileExist(const std::string &filename) const;
+        bool dirExist(const std::string &dirpath) const;
+        bool deleteDir(const std::string &dirpath) const;
+        int openFile(const std::string &filename);
+        bool createFile(const std::string &filename);
+        bool setFileLabel(const std::string &filename, const std::string &label) const;
+        bool getFileLabel(const std::string &filename);
+        bool checkFileNameSyntax(const std::string &filename) const;
+
+        uid_t m_fileUID;
+        gid_t m_fileGID;
+        mode_t m_fileMode;
+        std::string m_fileSmackLabel;
+
+        SockCred m_sockCred;
+    };
+}
+
+#endif // _OPEN_FOR_MANAGER_H_
diff --git a/src/server/service/open-for.cpp b/src/server/service/open-for.cpp
new file mode 100644 (file)
index 0000000..4a6a64a
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        open-for.cpp
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of open-for service
+ */
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+
+#include <protocols.h>
+#include <open-for.h>
+#include <unistd.h>
+#include <algorithm>
+
+#include <security-server.h>
+#include <security-server-util.h>
+
+namespace {
+// Service may open more than one socket.
+// These ID's will be assigned to sockets
+// and will be used only by service.
+// When new connection arrives, AcceptEvent
+// will be generated with proper ID to inform
+// service about input socket.
+//
+// Please note: SocketManaged does not use it and
+// does not check it in any way.
+//
+// If your service require only one socket
+// (uses only one socket labeled with smack)
+// you may ignore this ID (just pass 0)
+const int SERVICE_SOCKET_ID = 0;
+
+} // namespace anonymous
+
+namespace SecurityServer {
+
+OpenForService::OpenForConnInfo::~OpenForConnInfo() {
+    std::for_each(descriptorsVector.begin(),descriptorsVector.end(), ::close);
+}
+
+GenericSocketService::ServiceDescriptionVector OpenForService::GetServiceDescription() {
+    return ServiceDescriptionVector
+        {{SERVICE_SOCKET_OPEN_FOR, "security-server::api-open-for", SERVICE_SOCKET_ID, true}};
+}
+
+void OpenForService::accept(const AcceptEvent &event)
+{
+    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+}
+
+void OpenForService::write(const WriteEvent &event)
+{
+    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+void OpenForService::process(const ReadEvent &event)
+{
+    LogDebug("Read event for counter: " << event.connectionID.counter);
+    auto &info = m_connectionInfoMap[event.connectionID.counter];
+    info.buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, info.buffer, info.descriptorsVector));
+}
+
+void OpenForService::close(const CloseEvent &event)
+{
+    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    auto &descVector = m_connectionInfoMap[event.connectionID.counter].descriptorsVector;
+
+    for (auto iter = descVector.begin(); iter != descVector.end(); ++iter)
+        TEMP_FAILURE_RETRY(::close(*iter));
+
+    m_connectionInfoMap.erase(event.connectionID.counter);
+}
+
+bool OpenForService::processOne(const ConnectionID &conn, MessageBuffer &buffer, std::vector<int> &descVector)
+{
+    LogDebug("Iteration begin");
+
+    std::string filename;
+    MessageBuffer sendBuffer;
+
+    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+    int fd = -1;
+
+    if (!buffer.Ready())
+        return false;
+
+    Try {
+        Deserialization::Deserialize(buffer, filename);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogError("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    retCode = m_sharedFile.getFD(filename, conn.sock, fd);
+    if (fd != -1)
+        descVector.push_back(fd);
+    SendMsgData sendMsgData(retCode, fd);
+
+    m_serviceManager->Write(conn, sendMsgData);
+
+    return true;
+}
+
+} // namespace SecurityServer
diff --git a/src/server/service/open-for.h b/src/server/service/open-for.h
new file mode 100644 (file)
index 0000000..5ae0884
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        open-for.h
+ * @author      Zigniew Jasinski (z.jasinski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of open-for service
+ */
+
+#ifndef _SECURITY_SERVER_OPEN_FOR_
+#define _SECURITY_SERVER_OPEN_FOR_
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+#include <message-buffer.h>
+
+#include "open-for-manager.h"
+
+namespace SecurityServer
+{
+    class OpenForService
+      : public SecurityServer::GenericSocketService
+      , public SecurityServer::ServiceThread<OpenForService>
+    {
+    public:
+        //service functions
+        ServiceDescriptionVector GetServiceDescription();
+
+        DECLARE_THREAD_EVENT(AcceptEvent, accept)
+        DECLARE_THREAD_EVENT(WriteEvent, write)
+        DECLARE_THREAD_EVENT(ReadEvent, process)
+        DECLARE_THREAD_EVENT(CloseEvent, close)
+
+        void accept(const AcceptEvent &event);
+        void write(const WriteEvent &event);
+        void process(const ReadEvent &event);
+        void close(const CloseEvent &event);
+
+    private:
+        typedef std::vector<int> DescriptorVector;
+
+        struct OpenForConnInfo {
+            ~OpenForConnInfo();
+
+            DescriptorVector descriptorsVector;
+            MessageBuffer buffer;
+        };
+
+        typedef std::map<int, OpenForConnInfo> OpenForConnInfoMap;
+
+        //internal service functions
+        bool processOne(const ConnectionID &conn, MessageBuffer &buffer, DescriptorVector &descVector);
+
+        OpenForConnInfoMap m_connectionInfoMap;
+        SharedFile m_sharedFile;
+    };
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_OPEN_FOR_
diff --git a/src/server/service/password-exception.h b/src/server/service/password-exception.h
new file mode 100644 (file)
index 0000000..7679ebd
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password-exception.h
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Definition of PasswordException class.
+ */
+
+#ifndef _PASSWORD_EXCEPTION_H_
+#define _PASSWORD_EXCEPTION_H_
+
+#include <dpl/exception.h>
+
+namespace SecurityServer
+{
+    class PasswordException
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, OutOfData)
+        DECLARE_EXCEPTION_TYPE(Base, NoData)
+        DECLARE_EXCEPTION_TYPE(Base, FStreamOpenError)
+        DECLARE_EXCEPTION_TYPE(Base, FStreamWriteError)
+        DECLARE_EXCEPTION_TYPE(Base, FStreamReadError)
+        DECLARE_EXCEPTION_TYPE(Base, MemoryError)
+        DECLARE_EXCEPTION_TYPE(Base, NoPasswords)
+        DECLARE_EXCEPTION_TYPE(Base, PasswordNotActive)
+        DECLARE_EXCEPTION_TYPE(Base, MakeDirError)
+        DECLARE_EXCEPTION_TYPE(Base, TimerError)
+    };
+} //namespace SecurityServer
+
+#endif //_PASSWORD_EXCEPTION_H_
diff --git a/src/server/service/password-file-buffer.cpp b/src/server/service/password-file-buffer.cpp
new file mode 100644 (file)
index 0000000..eb97897
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password-file-buffer.h
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of PasswordFileBuffer, used for serialization in PasswordFile class
+ */
+
+#include <password-file-buffer.h>
+
+#include <fstream>
+#include <iterator>
+
+#include <dpl/log/log.h>
+
+#include <security-server.h>
+#include <password-exception.h>
+
+namespace SecurityServer
+{
+    PasswordFileBuffer::PasswordFileBuffer(): m_bufferReadBytes(0) {}
+
+    void PasswordFileBuffer::Read(size_t num, void *bytes)
+    {
+        if(m_buffer.empty()) {
+            LogError("Buffer doesn't contain any data.");
+            Throw(PasswordException::NoData);
+        }
+
+        if((m_bufferReadBytes + num) > m_buffer.size()) {
+            LogError("Not enough buffer to read " << num << " data.");
+            Throw(PasswordException::OutOfData);
+        }
+
+        void* ret = memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
+
+        if(ret == 0) {
+            LogError("Failed to read " << num << " bytes.");
+            Throw(PasswordException::MemoryError);
+        }
+
+        m_bufferReadBytes += num;
+    }
+
+    void PasswordFileBuffer::Write(size_t num, const void *bytes)
+    {
+        const char* buffer = static_cast<const char*>(bytes);
+        std::copy(buffer, buffer+num, std::back_inserter(m_buffer));
+    }
+
+    void PasswordFileBuffer::Save(const std::string &path)
+    {
+        std::ofstream file(path, std::ofstream::trunc);
+
+        if(!file.good()) {
+            LogError("Error while opening file stream.");
+            Throw(PasswordException::FStreamOpenError);
+        }
+
+        file.write(m_buffer.data(), m_buffer.size());
+        if(!file) {
+            LogError("Failed to write data.");
+            Throw(PasswordException::FStreamWriteError);
+        }
+    }
+
+    void PasswordFileBuffer::Load(const std::string &path)
+    {
+        std::ifstream file(path, std::ifstream::binary);
+
+        if(!file.good()) {
+            LogError("Error while opening file stream.");
+            Throw(PasswordException::FStreamOpenError);
+        }
+
+        //reset read bytes counter
+        m_bufferReadBytes = 0;
+
+        m_buffer.assign(std::istreambuf_iterator<char>(file),
+                        std::istreambuf_iterator<char>());
+
+        if(!file) {
+            LogError("Failed to read data. Failbit: " << file.fail() << ", Badbit: " << file.bad());
+            Throw(PasswordException::FStreamReadError);
+        }
+    }
+
+} //namespace SecurityServer
diff --git a/src/server/service/password-file-buffer.h b/src/server/service/password-file-buffer.h
new file mode 100644 (file)
index 0000000..419f142
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password-file-buffer.h
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of password file buffer, used for serialization in password-manager.h
+ */
+
+#ifndef _PASSWORD_FILE_BUFFER_H_
+#define _PASSWORD_FILE_BUFFER_H_
+
+#include <stddef.h>
+#include <vector>
+#include <string>
+
+#include <dpl/serialization.h>
+
+namespace SecurityServer
+{
+    class PasswordFileBuffer: public IStream
+    {
+    public:
+        PasswordFileBuffer();
+
+        virtual void Read(size_t num, void *bytes);
+        virtual void Write(size_t num, const void *bytes);
+
+        void Save(const std::string &path);
+        void Load(const std::string &path);
+
+    private:
+        typedef std::vector<char> DataBuffer;
+
+        DataBuffer m_buffer;
+        size_t m_bufferReadBytes;
+    };
+} //namespace SecurityServer
+
+#endif
diff --git a/src/server/service/password-file.cpp b/src/server/service/password-file.cpp
new file mode 100644 (file)
index 0000000..5f20fc2
--- /dev/null
@@ -0,0 +1,329 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password-file.cpp
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of PasswordFile, used to manage password files.
+ */
+#include <password-file.h>
+
+#include <fstream>
+#include <algorithm>
+
+#include <openssl/sha.h>
+
+#include <sys/stat.h>
+
+#include <dpl/log/log.h>
+
+#include <security-server.h>
+#include <password-exception.h>
+#include <password-file-buffer.h>
+
+const std::string DATA_DIR = "/opt/data/security-server";
+const std::string PASSWORD_FILE = "password.pwd";
+const std::string ATTEMPT_FILE = "attempt";
+const double RETRY_TIMEOUT = 0.5;
+
+namespace SecurityServer
+{
+    PasswordFile::Password::Password()
+    {
+        m_password = PasswordFile::hashPassword("");
+    }
+
+    PasswordFile::Password::Password(const RawHash& password)
+    {
+        m_password = password;
+    }
+
+    PasswordFile::Password::Password(IStream& stream)
+    {
+        Deserialization::Deserialize(stream, m_password);
+    }
+
+    void PasswordFile::Password::Serialize(IStream &stream) const
+    {
+        Serialization::Serialize(stream, m_password);
+    }
+
+    PasswordFile::PasswordFile(): m_maxAttempt(0), m_historySize(0),  m_expireTime(0), m_attempt(0)
+    {
+        // check if data directory exists
+        // if not create it
+        if (!dirExists(DATA_DIR.c_str())) {
+            if(mkdir(DATA_DIR.c_str(), 0700)) {
+                LogError("Failed to create directory for files. Error: " << strerror(errno));
+                Throw(PasswordException::MakeDirError);
+            }
+        }
+
+        preparePwdFile();
+        prepareAttemptFile();
+        resetTimer();
+    }
+
+    void PasswordFile::resetTimer()
+    {
+        m_retryTimerStart = std::chrono::monotonic_clock::now();
+        m_retryTimerStart -= TimeDiff(RETRY_TIMEOUT);
+    }
+
+    void PasswordFile::preparePwdFile()
+    {
+        std::string s_pwdfilePath = DATA_DIR + "/" + PASSWORD_FILE;
+
+        // check if password file exists
+        // if not create it
+        if (!fileExists(s_pwdfilePath)) {
+            LogSecureDebug("PWD_DBG not found password file. Creating.");
+            __mode_t oldMask = umask(S_IRUSR | S_IWUSR);
+
+            //create file
+            writeMemoryToFile();
+
+            umask(oldMask);
+        } else {     //if file exists, load data
+            LogSecureDebug("PWD_DBG found password file. Opening.");
+            loadMemoryFromFile();
+        }
+    }
+
+    void PasswordFile::prepareAttemptFile()
+    {
+        std::string s_attemptfilePath = DATA_DIR + "/" + ATTEMPT_FILE;
+
+        // check if attempt file exists
+        // if not create it
+        if (!fileExists(s_attemptfilePath)) {
+            LogSecureDebug("PWD_DBG not found attempt file. Creating.");
+            __mode_t oldMask = umask(S_IRUSR | S_IWUSR);
+
+            writeAttemptToFile();
+
+            umask(oldMask);
+        } else {
+            LogSecureDebug("PWD_DBG found attempt file. Opening.");
+            std::ifstream attemptFile(s_attemptfilePath);
+            if(!attemptFile.good()) {
+                LogError("Failed to open attempt file.");
+                Throw(PasswordException::FStreamOpenError);
+            }
+
+            attemptFile.read(reinterpret_cast<char*>(&m_attempt), sizeof(unsigned int));
+            if(!attemptFile) {
+                LogError("Failed to read attempt count.");
+                Throw(PasswordException::FStreamReadError);
+            }
+        }
+    }
+
+    bool PasswordFile::fileExists(const std::string &filename) const
+    {
+        struct stat buf;
+
+        return ((stat(filename.c_str(), &buf) == 0));
+    }
+
+    bool PasswordFile::dirExists(const std::string &dirpath) const
+    {
+        struct stat buf;
+
+        return ((stat(dirpath.c_str(), &buf) == 0) && (((buf.st_mode) & S_IFMT) == S_IFDIR));
+    }
+
+    void PasswordFile::writeMemoryToFile() const
+    {
+        PasswordFileBuffer pwdBuffer;
+
+        //serialize password attributes
+        Serialization::Serialize(pwdBuffer, m_maxAttempt);
+        Serialization::Serialize(pwdBuffer, m_historySize);
+        Serialization::Serialize(pwdBuffer, m_expireTime);
+        Serialization::Serialize(pwdBuffer, m_passwords);
+
+        pwdBuffer.Save(DATA_DIR + "/" + PASSWORD_FILE);
+    }
+
+    void PasswordFile::loadMemoryFromFile()
+    {
+        PasswordFileBuffer pwdFile;
+
+        pwdFile.Load(DATA_DIR + "/" + PASSWORD_FILE);
+
+        m_passwords.clear();
+
+        Deserialization::Deserialize(pwdFile, m_maxAttempt);
+        Deserialization::Deserialize(pwdFile, m_historySize);
+        Deserialization::Deserialize(pwdFile, m_expireTime);
+        Deserialization::Deserialize(pwdFile, m_passwords);
+    }
+
+    void PasswordFile::writeAttemptToFile() const
+    {
+        std::ofstream attemptFile(DATA_DIR + "/" + ATTEMPT_FILE, std::ofstream::trunc);
+
+        if(!attemptFile.good()) {
+            LogError("Failed to open attempt file.");
+            Throw(PasswordException::FStreamOpenError);
+        }
+
+        attemptFile.write(reinterpret_cast<const char*>(&m_attempt), sizeof(unsigned int));
+        if(!attemptFile) {
+            LogError("Failed to write attempt count.");
+            Throw(PasswordException::FStreamWriteError);
+        }
+    }
+
+    bool PasswordFile::isPasswordActive() const
+    {
+        return !(m_passwords.empty());
+    }
+
+    void PasswordFile::setHistory(unsigned int history)
+    {
+        //setting history should be independent from password being set
+        m_historySize = history;
+
+        //we want to keep 1 current pwd, plus history amount of passwords.
+        if(m_passwords.size() > 1+history)
+            m_passwords.resize(1+history);
+    }
+
+    unsigned int PasswordFile::getHistorySize() const
+    {
+        return m_historySize;
+    }
+
+    unsigned int PasswordFile::getAttempt() const
+    {
+        return m_attempt;
+    }
+
+    void PasswordFile::resetAttempt()
+    {
+        m_attempt = 0;
+    }
+
+    void PasswordFile::incrementAttempt()
+    {
+        m_attempt++;
+    }
+
+    int PasswordFile::getMaxAttempt() const
+    {
+        return m_maxAttempt;
+    }
+
+    void PasswordFile::setMaxAttempt(unsigned int maxAttempt)
+    {
+        m_maxAttempt = maxAttempt;
+    }
+
+    bool PasswordFile::isPasswordReused(const std::string &password) const
+    {
+        RawHash hashedPwd = hashPassword(password);
+
+        LogSecureDebug("PwdCount: " << m_passwords.size() << ", PwdMaxHistory: " << getHistorySize());
+
+        if(std::find_if(m_passwords.begin(), m_passwords.end(),
+                        [&hashedPwd](const Password& pwd) { return (pwd.m_password == hashedPwd); })
+                != m_passwords.end()) {
+            LogSecureDebug("Passwords match!");
+            return true;
+        }
+
+        LogSecureDebug("isPasswordReused: No passwords match, password not reused.");
+        return false;
+    }
+
+    void PasswordFile::setPassword(const std::string &password)
+    {
+        RawHash hashedPwd = hashPassword(password);
+
+        m_passwords.push_front(Password(hashedPwd));
+
+        //one current password, plus history amount of passwords
+        if(m_passwords.size() > 1+getHistorySize())
+            m_passwords.pop_back();
+    }
+
+    bool PasswordFile::checkPassword(const std::string &password) const
+    {
+        RawHash hashedPwd = hashPassword(password);
+
+        return (hashedPwd == m_passwords.begin()->m_password);
+    }
+
+    void PasswordFile::setExpireTime(int expireTime)
+    {
+        if(isPasswordActive())
+            m_expireTime = expireTime;
+        else {
+            LogError("Can't set expiration time, password not active.");
+            Throw(PasswordException::PasswordNotActive);
+        }
+    }
+
+    time_t PasswordFile::getExpireTime() const
+    {
+        return m_expireTime;
+    }
+
+    time_t PasswordFile::getExpireTimeLeft() const
+    {
+        if(m_expireTime > 0)
+            return (m_expireTime - time(NULL));
+        else
+            return m_expireTime;
+    }
+
+    bool PasswordFile::checkExpiration() const
+    {
+        //return true if expired, else false
+        return ((m_expireTime != 0) && (time(NULL) > m_expireTime));
+    }
+
+    bool PasswordFile::isIgnorePeriod() const
+    {
+        TimePoint retryTimerStop = std::chrono::monotonic_clock::now();
+        TimeDiff diff = retryTimerStop - m_retryTimerStart;
+
+        m_retryTimerStart = retryTimerStop;
+
+        return (diff.count() < RETRY_TIMEOUT);
+    }
+
+    //hashPassword is also used in Password struct constructor, that's why it's static. Moreover
+    //it is assumed that incorrect input password was checked earlier.
+    PasswordFile::RawHash PasswordFile::hashPassword(const std::string &password)
+    {
+        RawHash result(SHA256_DIGEST_LENGTH);
+
+        SHA256_CTX context;
+        SHA256_Init(&context);
+        SHA256_Update(&context, reinterpret_cast<const unsigned char*>(password.c_str()),
+                      password.size());
+        SHA256_Final(result.data(), &context);
+
+        return result;
+    }
+} //namespace SecurityServer
+
diff --git a/src/server/service/password-file.h b/src/server/service/password-file.h
new file mode 100644 (file)
index 0000000..216b9ab
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password-file.h
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of PasswordFile, used to manage password files.
+ */
+#ifndef _PASSWORD_FILE_H_
+#define _PASSWORD_FILE_H_
+
+#include <string>
+#include <vector>
+#include <list>
+#include <chrono>
+
+#include <time.h>
+
+#include <dpl/serialization.h>
+
+namespace SecurityServer
+{
+    class PasswordFile
+    {
+    public:
+        PasswordFile();
+
+        void writeMemoryToFile() const;
+        void writeAttemptToFile() const;
+
+        void setPassword(const std::string &password);
+        bool checkPassword(const std::string &password) const;
+        bool isPasswordActive() const;
+
+        void setHistory(unsigned int history);
+        unsigned int getHistorySize() const;
+
+        time_t getExpireTime() const;
+        time_t getExpireTimeLeft() const;
+        void setExpireTime(int expireTime);
+
+        //attempt manipulating functions
+        unsigned int getAttempt() const;
+        void resetAttempt();
+        void incrementAttempt();
+        int getMaxAttempt() const;
+        void setMaxAttempt(unsigned int maxAttempt);
+
+        bool isPasswordReused(const std::string &password) const;
+
+        bool checkExpiration() const;
+        bool isIgnorePeriod() const;
+
+    private:
+        typedef std::vector<unsigned char> RawHash;
+        typedef std::chrono::duration<double> TimeDiff;
+        typedef std::chrono::time_point<std::chrono::monotonic_clock, TimeDiff> TimePoint;
+
+        struct Password: public ISerializable
+        {
+            Password();
+            Password(const RawHash& password);
+            Password(IStream& stream);
+
+            virtual void Serialize(IStream &stream) const;
+
+            RawHash m_password;
+        };
+
+        typedef std::list<Password> PasswordList;
+
+        void loadMemoryFromFile();
+
+        void resetTimer();
+        void preparePwdFile();
+        void prepareAttemptFile();
+        bool fileExists(const std::string &filename) const;
+        bool dirExists(const std::string &dirpath) const;
+        static RawHash hashPassword(const std::string &password);
+
+        mutable TimePoint m_retryTimerStart;
+
+        //password file data
+        PasswordList m_passwords;
+        unsigned int m_maxAttempt;
+        unsigned int m_historySize;
+        time_t m_expireTime;
+
+        //attempt file data
+        unsigned int m_attempt;
+    };
+}    //namespace SecurityServer
+
+#endif
diff --git a/src/server/service/password-manager.cpp b/src/server/service/password-manager.cpp
new file mode 100644 (file)
index 0000000..23a4b14
--- /dev/null
@@ -0,0 +1,295 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password-manager.cpp
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of password management functions
+ */
+
+#include <password-manager.h>
+
+#include <iostream>
+#include <iterator>
+#include <algorithm>
+
+#include <limits.h>
+
+#include <dpl/log/log.h>
+
+#include <protocols.h>
+
+#include <security-server.h>
+
+namespace {
+    bool calculateExpiredTime(unsigned int receivedDays, unsigned int &validSecs)
+    {
+        validSecs = 0;
+
+        if(receivedDays == 0)
+            return true;
+
+        time_t curTime = time(NULL);
+
+        if (receivedDays > ((UINT_MAX - curTime) / 86400)) {
+            LogError("Incorrect input param.");
+            return false;
+        } else {
+            validSecs = (curTime + (receivedDays * 86400));
+            return true;
+        }
+
+        //when receivedDays equal to zero, it means infinite password valid time
+        //if receivedDays is 0 return true, else return false (that is, an error)
+        return false;
+    }
+} //namespace
+
+namespace SecurityServer
+{
+    int PasswordManager::isPwdValid(unsigned int &currentAttempt, unsigned int &maxAttempt,
+                                    unsigned int &expirationTime) const
+    {
+        if (m_pwdFile.isIgnorePeriod()) {
+            LogError("Retry timeout occured.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
+        }
+
+        if (!m_pwdFile.isPasswordActive()) {
+            LogError("Current password not active.");
+            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
+        } else {
+            currentAttempt = m_pwdFile.getAttempt();
+            maxAttempt = m_pwdFile.getMaxAttempt();
+            expirationTime = m_pwdFile.getExpireTimeLeft();
+
+            return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
+        }
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    int PasswordManager::checkPassword(const std::string &challenge, unsigned int &currentAttempt,
+                                       unsigned int &maxAttempt, unsigned int &expirationTime)
+    {
+        LogSecureDebug("Inside checkPassword function.");
+
+        if (m_pwdFile.isIgnorePeriod()) {
+            LogError("Retry timeout occurred.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
+        }
+
+        if (!m_pwdFile.isPasswordActive()) {
+            LogError("Password not active.");
+            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
+        }
+
+        currentAttempt = m_pwdFile.getAttempt();
+        maxAttempt = m_pwdFile.getMaxAttempt();
+        expirationTime = m_pwdFile.getExpireTimeLeft();
+
+        if ((maxAttempt != 0) && (currentAttempt >= maxAttempt)) {
+            LogError("Too many tries.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+        }
+
+        m_pwdFile.incrementAttempt();
+        m_pwdFile.writeAttemptToFile();
+
+        if (!m_pwdFile.checkPassword(challenge)) {
+            LogError("Wrong password.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
+        }
+
+        if (m_pwdFile.checkExpiration()) {
+            LogError("Password expired.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
+        }
+
+        m_pwdFile.resetAttempt();
+        m_pwdFile.writeAttemptToFile();
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    int PasswordManager::setPassword(const std::string &currentPassword,
+                                     const std::string &newPassword,
+                                     const unsigned int receivedAttempts,
+                                     const unsigned int receivedDays)
+    {
+        LogSecureDebug("Curpwd = " << currentPassword << ", newpwd = " << newPassword <<
+                       ", recatt = " << receivedAttempts << ", recdays = " << receivedDays);
+
+        unsigned int valid_secs = 0;
+
+        //check retry timer
+        if (m_pwdFile.isIgnorePeriod()) {
+            LogError("Retry timeout occured.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
+        }
+
+        //check if passwords are correct
+        if (currentPassword.size() > MAX_PASSWORD_LEN) {
+            LogError("Current password length failed.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        if (newPassword.size() > MAX_PASSWORD_LEN) {
+            LogError("New password length failed.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        //check delivered currentPassword
+        //when m_passwordActive flag is true, currentPassword shouldn't be empty
+        if (currentPassword.empty() && m_pwdFile.isPasswordActive()) {
+            LogError("Password is already set.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
+        }
+
+        // check attempt
+        unsigned int maxAttempt = m_pwdFile.getMaxAttempt();
+        if ((maxAttempt != 0) && (m_pwdFile.getAttempt() >= maxAttempt)) {
+            LogError("Too many attempts.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+        }
+
+        //if we didn't exceed max attempts, increment attempt count and save it to separate file
+        m_pwdFile.incrementAttempt();
+        m_pwdFile.writeAttemptToFile();
+
+        //check current password, however only when we don't send empty string as current.
+        if(!currentPassword.empty()) {
+            if(!m_pwdFile.checkPassword(currentPassword)) {
+                LogError("Wrong password.");
+                return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
+            }
+        }
+
+        //check if password expired
+        if (m_pwdFile.checkExpiration()) {
+            LogError("Password expired.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
+        }
+
+        //check history
+        if (m_pwdFile.isPasswordActive()) {
+            if (m_pwdFile.isPasswordReused(newPassword)) {
+                LogError("Password reused.");
+                return SECURITY_SERVER_API_ERROR_PASSWORD_REUSED;
+            }
+        }
+
+        if(!calculateExpiredTime(receivedDays, valid_secs)) {
+            LogError("Received expiration time incorrect.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        //setting password
+        m_pwdFile.setPassword(newPassword);
+        m_pwdFile.setMaxAttempt(receivedAttempts);
+        m_pwdFile.setExpireTime(valid_secs);
+        m_pwdFile.writeMemoryToFile();
+
+        m_pwdFile.resetAttempt();
+        m_pwdFile.writeAttemptToFile();
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    int PasswordManager::setPasswordValidity(const unsigned int receivedDays)
+    {
+        unsigned int valid_secs = 0;
+
+        LogSecureDebug("received_days: " << receivedDays);
+
+        if (!m_pwdFile.isPasswordActive()) {
+            LogError("Current password is not active.");
+            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
+        }
+
+        if(!calculateExpiredTime(receivedDays, valid_secs))
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+        m_pwdFile.setExpireTime(valid_secs);
+        m_pwdFile.writeMemoryToFile();
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    int PasswordManager::resetPassword(const std::string &newPassword,
+                                       const unsigned int receivedAttempts,
+                                       const unsigned int receivedDays)
+    {
+        unsigned int valid_secs = 0;
+
+        if (m_pwdFile.isIgnorePeriod()) {
+            LogError("Retry timeout occured.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
+        }
+
+        if(!calculateExpiredTime(receivedDays, valid_secs))
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+        m_pwdFile.setPassword(newPassword);
+        m_pwdFile.setMaxAttempt(receivedAttempts);
+        m_pwdFile.setExpireTime(valid_secs);
+        m_pwdFile.writeMemoryToFile();
+
+        m_pwdFile.resetAttempt();
+        m_pwdFile.writeAttemptToFile();
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    int PasswordManager::setPasswordHistory(const unsigned int history)
+    {
+        if(history > MAX_PASSWORD_HISTORY) {
+            LogError("Incorrect input param.");
+            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+        }
+
+        // check retry time
+        if (m_pwdFile.isIgnorePeriod()) {
+            LogError("Retry timeout occurred.");
+            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
+        }
+
+        m_pwdFile.setHistory(history);
+        m_pwdFile.writeMemoryToFile();
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+
+    int PasswordManager::setPasswordMaxChallenge(const unsigned int maxChallenge)
+    {
+        // check if there is password
+        if (!m_pwdFile.isPasswordActive()) {
+            LogError("Password not active.");
+            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
+        }
+
+        m_pwdFile.setMaxAttempt(maxChallenge);
+        m_pwdFile.writeMemoryToFile();
+
+        m_pwdFile.resetAttempt();
+        m_pwdFile.writeAttemptToFile();
+
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+} //namespace SecurityServer
diff --git a/src/server/service/password-manager.h b/src/server/service/password-manager.h
new file mode 100644 (file)
index 0000000..bef6521
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password-manager.h
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of password management functions
+ */
+
+#ifndef _PASSWORDMANAGER_H_
+#define _PASSWORDMANAGER_H_
+
+#include <string>
+
+#include <password-file.h>
+
+namespace SecurityServer
+{
+    class PasswordManager
+    {
+    public:
+        //checking functions
+        int isPwdValid(unsigned int &currentAttempt, unsigned int &maxAttempt,
+                       unsigned int &expirationTime) const;
+        int checkPassword(const std::string& challenge, unsigned int &currentAttempt,
+                          unsigned int &maxAttempt, unsigned int &expTime);
+        //no const in checkPassword, attempts are updated
+
+        //setting functions
+        int setPassword(const std::string &currentPassword, const std::string &newPassword,
+                        const unsigned int receivedAttempts, const unsigned int receivedDays);
+        int setPasswordValidity(const unsigned int receivedDays);
+        int resetPassword(const std::string &newPassword, const unsigned int receivedAttempts,
+                          const unsigned int receivedDays);
+        int setPasswordHistory(const unsigned int history);
+        int setPasswordMaxChallenge(const unsigned int maxChallenge);
+
+    private:
+        PasswordFile m_pwdFile;
+    };
+} //namespace SecurityServer
+
+#endif
diff --git a/src/server/service/password.cpp b/src/server/service/password.cpp
new file mode 100644 (file)
index 0000000..d0d4307
--- /dev/null
@@ -0,0 +1,261 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password.cpp
+ * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of password service
+ */
+
+#include <iostream>
+#include <string>
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+
+#include <password.h>
+
+#include <security-server.h>
+#include <password-exception.h>
+
+namespace SecurityServer {
+
+namespace {
+// Service may open more than one socket.
+// These ID's will be assigned to sockets
+// and will be used only by service.
+// When new connection arrives, AcceptEvent
+// will be generated with proper ID to inform
+// service about input socket.
+//
+// Please note: SocketManager does not use it and
+// does not check it in any way.
+//
+// If your service requires only one socket
+// (uses only one socket labeled with smack)
+// you may ignore this ID (just pass 0)
+const InterfaceID SOCKET_ID_CHECK   = 0;
+const InterfaceID SOCKET_ID_SET     = 1;
+
+} // namespace anonymous
+
+GenericSocketService::ServiceDescriptionVector PasswordService::GetServiceDescription()
+{
+    return ServiceDescriptionVector {
+        {SERVICE_SOCKET_PASSWD_CHECK, "security-server::api-password-check", SOCKET_ID_CHECK},
+        {SERVICE_SOCKET_PASSWD_SET,   "security-server::api-password-set",   SOCKET_ID_SET}
+    };
+}
+
+void PasswordService::accept(const AcceptEvent &event)
+{
+    LogSecureDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+
+    auto &info = m_connectionInfoMap[event.connectionID.counter];
+    info.interfaceID = event.interfaceID;
+}
+
+void PasswordService::write(const WriteEvent &event)
+{
+    LogSecureDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+void PasswordService::process(const ReadEvent &event)
+{
+    LogSecureDebug("Read event for counter: " << event.connectionID.counter);
+    auto &info = m_connectionInfoMap[event.connectionID.counter];
+    info.buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, info.buffer, info.interfaceID));
+}
+
+void PasswordService::close(const CloseEvent &event)
+{
+    LogSecureDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    m_connectionInfoMap.erase(event.connectionID.counter);
+}
+
+int PasswordService::processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer,
+                                            unsigned int &cur_att, unsigned int &max_att,
+                                            unsigned int &exp_time)
+{
+    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+    switch (hdr) {
+        case PasswordHdrs::HDR_IS_PWD_VALID:
+            result = m_pwdManager.isPwdValid(cur_att, max_att, exp_time);
+            break;
+
+        case PasswordHdrs::HDR_CHK_PWD: {
+            std::string challenge;
+            Deserialization::Deserialize(buffer, challenge);
+            result = m_pwdManager.checkPassword(challenge, cur_att, max_att, exp_time);
+            break;
+        }
+
+        default:
+            LogError("Unknown msg header.");
+            Throw(Exception::IncorrectHeader);
+    }
+
+    return result;
+}
+
+int PasswordService::processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer)
+{
+    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+    std::string curPwd, newPwd;
+    unsigned int rec_att = 0, rec_days = 0, rec_max_challenge = 0, rec_history = 0;
+
+    switch(hdr) {
+        case PasswordHdrs::HDR_SET_PWD:
+            Deserialization::Deserialize(buffer, curPwd);
+            Deserialization::Deserialize(buffer, newPwd);
+            Deserialization::Deserialize(buffer, rec_att);
+            Deserialization::Deserialize(buffer, rec_days);
+            result = m_pwdManager.setPassword(curPwd, newPwd, rec_att, rec_days);
+            break;
+
+        case PasswordHdrs::HDR_SET_PWD_VALIDITY:
+            Deserialization::Deserialize(buffer, rec_days);
+            result = m_pwdManager.setPasswordValidity(rec_days);
+            break;
+
+        case PasswordHdrs::HDR_SET_PWD_MAX_CHALLENGE:
+            Deserialization::Deserialize(buffer, rec_max_challenge);
+            result = m_pwdManager.setPasswordMaxChallenge(rec_max_challenge);
+            break;
+
+        case PasswordHdrs::HDR_RST_PWD:
+            Deserialization::Deserialize(buffer, newPwd);
+            Deserialization::Deserialize(buffer, rec_att);
+            Deserialization::Deserialize(buffer, rec_days);
+            result = m_pwdManager.resetPassword(newPwd, rec_att, rec_days);
+            break;
+
+        case PasswordHdrs::HDR_SET_PWD_HISTORY:
+            Deserialization::Deserialize(buffer, rec_history);
+            result = m_pwdManager.setPasswordHistory(rec_history);
+            break;
+
+        default:
+            LogError("Unknown msg header.");
+            Throw(Exception::IncorrectHeader);
+    }
+
+    return result;
+}
+
+bool PasswordService::processOne(const ConnectionID &conn, MessageBuffer &buffer,
+                                 InterfaceID interfaceID)
+{
+    LogSecureDebug("Iteration begin");
+
+    MessageBuffer sendBuffer;
+
+    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+    unsigned int cur_att = 0, max_att = 0, exp_time = 0;
+
+    if (!buffer.Ready())
+        return false;
+
+    Try {       //try..catch for MessageBuffer errors, closes connection when exception is thrown
+        int tempHdr;
+        Deserialization::Deserialize(buffer, tempHdr);
+        PasswordHdrs hdr = static_cast<PasswordHdrs>(tempHdr);
+
+        try {   //try..catch for internal service errors, assigns error code for returning.
+            switch (interfaceID) {
+                case SOCKET_ID_CHECK:
+                    retCode = processCheckFunctions(hdr, buffer, cur_att, max_att, exp_time);
+                    break;
+
+                case SOCKET_ID_SET:
+                    retCode = processSetFunctions(hdr, buffer);
+                    break;
+
+                default:
+                    LogError("Wrong interfaceID.");
+                    Throw(Exception::IncorrectHeader);
+            }
+        } catch (PasswordException::Base &e) {
+            LogError("Password error: " << e.DumpToString());
+            retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+        } catch (std::exception &e) {
+            LogError("STD error: " << e.what());
+            retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+        }
+
+        //everything is OK, send return code and extra data
+        Serialization::Serialize(sendBuffer, retCode);
+
+        //Returning additional information should occur only when checking functions
+        //are called, and under certain return values
+        if(interfaceID == SOCKET_ID_CHECK)
+        {
+            switch(retCode)
+            {
+            case SECURITY_SERVER_API_ERROR_PASSWORD_EXIST:
+            case SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH:
+            case SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+            case SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED:
+                Serialization::Serialize(sendBuffer, cur_att);
+                Serialization::Serialize(sendBuffer, max_att);
+                Serialization::Serialize(sendBuffer, exp_time);
+                break;
+
+            case SECURITY_SERVER_API_SUCCESS:
+                if(hdr == PasswordHdrs::HDR_CHK_PWD) {
+                    Serialization::Serialize(sendBuffer, cur_att);
+                    Serialization::Serialize(sendBuffer, max_att);
+                    Serialization::Serialize(sendBuffer, exp_time);
+                }
+                break;
+
+            default:
+                break;
+            }
+        }
+
+        m_serviceManager->Write(conn, sendBuffer.Pop());
+    } Catch (MessageBuffer::Exception::Base) {
+        LogError("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    } Catch (PasswordService::Exception::Base) {
+        LogError("Incorrect message header. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+
+
+    return true;
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/service/password.h b/src/server/service/password.h
new file mode 100644 (file)
index 0000000..0989d81
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        password.h
+ * @author      Zigniew Jasinski (z.jasinski@samsung.com)
+ * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
+ * @version     1.0
+ * @brief       Implementation of password service
+ */
+
+#ifndef _SECURITY_SERVER_PASSWORD_
+#define _SECURITY_SERVER_PASSWORD_
+
+#include <map>
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+#include <message-buffer.h>
+#include <connection-info.h>
+#include <protocols.h>
+
+#include <password-manager.h>
+
+namespace SecurityServer
+{
+    class PasswordService
+      : public SecurityServer::GenericSocketService
+      , public SecurityServer::ServiceThread<PasswordService>
+    {
+    public:
+        class Exception
+        {
+        public:
+            DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
+            DECLARE_EXCEPTION_TYPE(Base, IncorrectHeader)
+        };
+
+        //service functions
+        ServiceDescriptionVector GetServiceDescription();
+
+        DECLARE_THREAD_EVENT(AcceptEvent, accept)
+        DECLARE_THREAD_EVENT(WriteEvent, write)
+        DECLARE_THREAD_EVENT(ReadEvent, process)
+        DECLARE_THREAD_EVENT(CloseEvent, close)
+
+        void accept(const AcceptEvent &event);
+        void write(const WriteEvent &event);
+        void process(const ReadEvent &event);
+        void close(const CloseEvent &event);
+
+    private:
+        //internal service functions
+        bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
+        int processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer, unsigned int &cur_att,
+                                   unsigned int &max_att, unsigned int &exp_time);
+        int processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer);
+
+        // service attributes
+        PasswordManager m_pwdManager;
+        ConnectionInfoMap m_connectionInfoMap;
+    };
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_PASSWORD_
diff --git a/src/server/service/privilege-by-pid.cpp b/src/server/service/privilege-by-pid.cpp
new file mode 100644 (file)
index 0000000..1a30172
--- /dev/null
@@ -0,0 +1,165 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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        privilege-by-pid.cpp
+ * @author      Jan Cybulski (j.cybulski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of check-privilege-by-pid service.
+ */
+
+#include <sys/smack.h>
+
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+
+#include <protocols.h>
+#include <privilege-by-pid.h>
+
+#include <security-server.h>
+#include <security-server-util.h>
+#include <smack-check.h>
+
+#include <privilege-control.h>
+
+namespace SecurityServer {
+
+GenericSocketService::ServiceDescriptionVector PrivilegeByPidService::GetServiceDescription() {
+    //TODO: after enabled smack protection for api use "security-server::api-privilege-by-pid"
+    return ServiceDescriptionVector
+        {{SERVICE_SOCKET_PRIVILEGE_BY_PID, "*" }};
+}
+
+void PrivilegeByPidService::accept(const AcceptEvent &event) {
+    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+        << " ConnectionID.counter: " << event.connectionID.counter
+        << " ServiceID: " << event.interfaceID);
+}
+
+void PrivilegeByPidService::write(const WriteEvent &event) {
+    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+        " Size: " << event.size << " Left: " << event.left);
+    if (event.left == 0)
+        m_serviceManager->Close(event.connectionID);
+}
+
+bool PrivilegeByPidService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
+    LogDebug("Iteration begin");
+
+    int retval;
+    int pid;
+    std::string object;
+    std::string access_rights;
+    char subject[SMACK_LABEL_LEN + 1] = {0};
+
+    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+
+
+    if (!buffer.Ready()) {
+        return false;
+    }
+
+    Try {
+        Deserialization::Deserialize(buffer, pid);
+        Deserialization::Deserialize(buffer, object);
+        Deserialization::Deserialize(buffer, access_rights);
+    } Catch (MessageBuffer::Exception::Base) {
+        LogDebug("Broken protocol. Closing socket.");
+        m_serviceManager->Close(conn);
+        return false;
+    }
+
+    if (smack_check()) {
+        retval = smack_pid_have_access(pid, object.c_str(), access_rights.c_str());
+        LogDebug("smack_pid_have_access returned " << retval);
+
+        if (get_smack_label_from_process(pid, subject) != PC_OPERATION_SUCCESS) {
+            // subject label is set to empty string
+            LogError("get_smack_label_from_process failed. Subject label has not been read.");
+        } else {
+            LogSecureDebug("Subject label of client PID " << pid << " is: " << subject);
+        }
+    } else {
+        LogDebug("SMACK is not available. Subject label has not been read.");
+        retval = 1;
+    }
+//    char *path = read_exe_path_from_proc(pid);
+//
+//    if (retval > 0)
+//        LogDebug("SS_SMACK: "
+//                << "caller_pid=" << pid
+//                << ", subject=" << subject
+//                << ", object=" << object
+//                << ", access=" << access_rights
+//                << ", result=" << retval
+//                << ", caller_path=" << path);
+//    else
+//        LogError("SS_SMACK: "
+//                << "caller_pid=" << pid
+//                << ", subject=" << subject
+//                << ", object=" << object
+//                << ", access=" << access_rights
+//                << ", result=" << retval
+//                << ", caller_path=" << path);
+//
+//    if (path != NULL)
+//        free(path);
+
+
+    if (retval == 1)   //there is permission
+        retCode = SECURITY_SERVER_API_SUCCESS;
+    else                //there is no permission
+        retCode = SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
+
+    MessageBuffer sendBuffer;
+    Serialization::Serialize(sendBuffer, retCode);
+    m_serviceManager->Write(conn, sendBuffer.Pop());
+
+    if (retval != 1) {
+        char *path = read_exe_path_from_proc(pid);
+
+        LogSmackAudit("SS_SMACK: "
+            << "caller_pid=" << pid
+            << ", subject="  << subject
+            << ", object="   << object
+            << ", access="   << access_rights
+            << ", result="   << retval
+            << ", caller_path=" << (path ? path : ""));
+
+        free(path);
+    }
+
+    return true;
+}
+
+void PrivilegeByPidService::process(const ReadEvent &event) {
+    LogDebug("Read event for counter: " << event.connectionID.counter);
+    auto &buffer = m_messageBufferMap[event.connectionID.counter];
+    buffer.Push(event.rawBuffer);
+
+    // We can get several requests in one package.
+    // Extract and process them all
+    while(processOne(event.connectionID, buffer));
+}
+
+void PrivilegeByPidService::close(const CloseEvent &event) {
+    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+    m_messageBufferMap.erase(event.connectionID.counter);
+}
+
+} // namespace SecurityServer
+
diff --git a/src/server/service/privilege-by-pid.h b/src/server/service/privilege-by-pid.h
new file mode 100644 (file)
index 0000000..da5cdde
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  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
+ */
+/*hcpp
+ * @author      Jan Cybulski (j.cybulski@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of api-check-privilege-by-pid
+ */
+
+#ifndef _SECURITY_SERVER_PRIVILEGE_BY_PID_
+#define _SECURITY_SERVER_PRIVILEGE_BY_PID_
+
+#include <service-thread.h>
+#include <generic-socket-manager.h>
+
+#include <message-buffer.h>
+
+namespace SecurityServer {
+
+class PrivilegeByPidService
+  : public SecurityServer::GenericSocketService
+  , public SecurityServer::ServiceThread<PrivilegeByPidService>
+{
+public:
+    typedef std::map<int, MessageBuffer> MessageBufferMap;
+
+    ServiceDescriptionVector GetServiceDescription();
+
+    DECLARE_THREAD_EVENT(AcceptEvent, accept)
+    DECLARE_THREAD_EVENT(WriteEvent, write)
+    DECLARE_THREAD_EVENT(ReadEvent, process)
+    DECLARE_THREAD_EVENT(CloseEvent, close)
+
+    void accept(const AcceptEvent &event);
+    void write(const WriteEvent &event);
+    void process(const ReadEvent &event);
+    void close(const CloseEvent &event);
+private:
+    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
+
+    MessageBufferMap m_messageBufferMap;
+};
+
+} // namespace SecurityServer
+
+#endif // _SECURITY_SERVER_DATA_SHARE_
diff --git a/src/server2/CMakeLists.txt b/src/server2/CMakeLists.txt
deleted file mode 100644 (file)
index b24dd24..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-PKG_CHECK_MODULES(COMMON_DEP
-    dlog
-    REQUIRED
-    )
-
-SET(COMMON_PATH ${PROJECT_SOURCE_DIR}/src/server2)
-
-SET(COMMON_SOURCES
-    ${COMMON_PATH}/common/protocols.cpp
-    ${COMMON_PATH}/common/message-buffer.cpp
-    ${COMMON_PATH}/dpl/log/src/abstract_log_provider.cpp
-    ${COMMON_PATH}/dpl/log/src/dlog_log_provider.cpp
-    ${COMMON_PATH}/dpl/log/src/log.cpp
-    ${COMMON_PATH}/dpl/log/src/old_style_log_provider.cpp
-    ${COMMON_PATH}/dpl/log/src/audit-smack-log.cpp
-    ${COMMON_PATH}/dpl/core/src/assert.cpp
-    ${COMMON_PATH}/dpl/core/src/binary_queue.cpp
-    ${COMMON_PATH}/dpl/core/src/colors.cpp
-    ${COMMON_PATH}/dpl/core/src/exception.cpp
-    ${COMMON_PATH}/dpl/core/src/noncopyable.cpp
-    ${COMMON_PATH}/dpl/core/src/serialization.cpp
-    ${COMMON_PATH}/dpl/core/src/singleton.cpp
-    )
-
-INCLUDE_DIRECTORIES(SYSTEM
-    ${COMMON_DEP_INCLUDE_DIRS}
-    )
-
-INCLUDE_DIRECTORIES(
-    ${COMMON_PATH}/common
-    ${COMMON_PATH}/dpl/core/include
-    ${COMMON_PATH}/dpl/log/include
-    )
-
-ADD_LIBRARY(${TARGET_SERVER_COMMON} SHARED ${COMMON_SOURCES})
-
-SET_TARGET_PROPERTIES(
-    ${TARGET_SERVER_COMMON}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=default"
-        SOVERSION 1.0.0
-        VERSION 1.0.0
-    )
-
-TARGET_LINK_LIBRARIES(${TARGET_SERVER_COMMON}
-    ${COMMON_DEP_LIBRARIES}
-    )
-
-################################################################################
-
-INSTALL(TARGETS ${TARGET_SERVER_COMMON} DESTINATION lib)
-
diff --git a/src/server2/client/client-app-permissions.cpp b/src/server2/client/client-app-permissions.cpp
deleted file mode 100644 (file)
index 05b07d3..0000000
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-app-permissions.cpp
- * @author      Pawel Polawski (pawel.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This file contain implementation of security_server_app_enable_permissions
- *              and security_server_app_disable functions
- */
-
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <privilege-control.h>
-#include <security-server.h>
-#include <security-server-common.h>
-
-
-SECURITY_SERVER_API
-int security_server_app_enable_permissions(const char *app_id, app_type_t app_type, const char **perm_list, int persistent)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    std::vector<std::string> permissions_list;
-
-    LogDebug("security_server_app_enable_permissions() called");
-
-    return try_catch([&] {
-        if ((NULL == app_id) || (strlen(app_id) == 0)) {
-            LogDebug("App_id is NULL");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-        if ((NULL == perm_list) || (strlen(perm_list[0]) == 0)) {
-            LogDebug("Perm_list is NULL");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        LogDebug("app_type: " << (int)app_type);
-        LogDebug("persistent: " << persistent);
-        LogDebug("app_id: " << app_id);
-
-        //put all strings in STL vector
-        for (int i = 0; perm_list[i] != NULL; i++) {
-            LogDebug("perm_list[" << i << "]: " << perm_list[i]);
-            permissions_list.push_back(std::string(perm_list[i]));
-        }
-
-        //put data into buffer
-        Serialization::Serialize(send, (int)AppPermissionsAction::ENABLE);   //works as a MSG_ID
-        Serialization::Serialize(send, persistent);
-        Serialization::Serialize(send, (int)app_type);
-        Serialization::Serialize(send, std::string(app_id));
-        Serialization::Serialize(send, permissions_list);
-
-        //send buffer to server
-        int result = sendToServer(SERVICE_SOCKET_APP_PERMISSIONS, send.Pop(), recv);
-        if (result != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << result);
-            return result;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, result);
-        return result;
-    });
-}
-
-
-SECURITY_SERVER_API
-int security_server_app_disable_permissions(const char *app_id, app_type_t app_type, const char **perm_list)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    std::vector<std::string> permissions_list;
-
-    LogDebug("security_server_app_disable_permissions() called");
-
-    return try_catch([&] {
-        if ((NULL == app_id) || (strlen(app_id) == 0)) {
-            LogDebug("App_id is NULL");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-        if ((NULL == perm_list) || (strlen(perm_list[0]) == 0)) {
-            LogDebug("Perm_list is NULL");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        LogDebug("app_type: " << (int)app_type);
-        LogDebug("app_id: " << app_id);
-
-        //put all strings in STL vector
-        for (int i = 0; perm_list[i] != NULL; i++) {
-            LogDebug("perm_list[" << i << "]: " << perm_list[i]);
-            permissions_list.push_back(std::string(perm_list[i]));
-        }
-
-        //put data into buffer
-        Serialization::Serialize(send, (int)AppPermissionsAction::DISABLE);   //works as a MSG_ID
-        Serialization::Serialize(send, (int)app_type);
-        Serialization::Serialize(send, std::string(app_id));
-        Serialization::Serialize(send, permissions_list);
-
-        //send buffer to server
-        int result = sendToServer(SERVICE_SOCKET_APP_PERMISSIONS, send.Pop(), recv);
-        if (result != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << result);
-            return result;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, result);
-        return result;
-    });
-}
-
-
-SECURITY_SERVER_API
-int security_server_app_has_privilege(const char *app_id,
-                                      app_type_t app_type,
-                                      const char *privilege_name,
-                                      int *result)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-
-    LogDebug("security_server_app_has_privilege() called");
-
-    try {
-        if ((NULL == app_id) || (strlen(app_id) == 0)) {
-            LogError("app_id is NULL or empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-        if ((NULL == privilege_name) || (strlen(privilege_name) == 0)) {
-            LogError("privilege_name is NULL or empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-        if (NULL == result) {
-            LogError("result is NULL");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        LogDebug("app_id: " << app_id);
-        LogDebug("app_type: " << static_cast<int>(app_type));
-        LogDebug("privilege_name: " << privilege_name);
-
-        //put data into buffer
-        Serialization::Serialize(send, static_cast<int>(PrivilegeCheckHdrs::CHECK_GIVEN_APP));
-        Serialization::Serialize(send, std::string(app_id));
-        Serialization::Serialize(send, static_cast<int>(app_type));
-        Serialization::Serialize(send, std::string(privilege_name));
-
-        //send buffer to server
-        int apiResult = sendToServer(SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME, send.Pop(), recv);
-        if (apiResult != SECURITY_SERVER_API_SUCCESS) {
-            LogError("Error in sendToServer. Error code: " << apiResult);
-            return apiResult;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, apiResult);
-        if (apiResult == SECURITY_SERVER_API_SUCCESS) {
-            Deserialization::Deserialize(recv, *result);
-        }
-        return apiResult;
-
-    } catch (MessageBuffer::Exception::Base &e) {
-        LogError("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
-    } catch (std::exception &e) {
-        LogError("STD exception " << e.what());
-    } catch (...) {
-        LogError("Unknown exception occured");
-    }
-
-    return SECURITY_SERVER_API_ERROR_UNKNOWN;
-}
-
-
-SECURITY_SERVER_API
-int security_server_app_caller_has_privilege(app_type_t app_type,
-                                             const char *privilege_name,
-                                             int *result)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-
-    LogDebug("security_server_app_caller_has_privilege() called");
-
-    try {
-        if ((NULL == privilege_name) || (strlen(privilege_name) == 0)) {
-            LogError("privilege_name is NULL or empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-        if (NULL == result) {
-            LogError("result is NULL");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        LogDebug("app_type: " << static_cast<int>(app_type));
-        LogDebug("privilege_name: " << privilege_name);
-
-        //put data into buffer
-        Serialization::Serialize(send, static_cast<int>(PrivilegeCheckHdrs::CHECK_CALLER_APP));
-        Serialization::Serialize(send, static_cast<int>(app_type));
-        Serialization::Serialize(send, std::string(privilege_name));
-
-        //send buffer to server
-        int apiResult = sendToServer(SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME, send.Pop(), recv);
-        if (apiResult != SECURITY_SERVER_API_SUCCESS) {
-            LogError("Error in sendToServer. Error code: " << apiResult);
-            return apiResult;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, apiResult);
-        if (apiResult == SECURITY_SERVER_API_SUCCESS) {
-            Deserialization::Deserialize(recv, *result);
-        }
-        return apiResult;
-
-    } catch (MessageBuffer::Exception::Base &e) {
-        LogError("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
-    } catch (std::exception &e) {
-        LogError("STD exception " << e.what());
-    } catch (...) {
-        LogError("Unknown exception occured");
-    }
-
-    return SECURITY_SERVER_API_ERROR_UNKNOWN;
-}
diff --git a/src/server2/client/client-common.cpp b/src/server2/client/client-common.cpp
deleted file mode 100644 (file)
index 2bd9091..0000000
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-common.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This file is implementation of client-common functions.
- */
-
-#include <fcntl.h>
-#include <poll.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <unistd.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-#include <dpl/singleton.h>
-#include <dpl/singleton_safe_impl.h>
-
-#include <message-buffer.h>
-
-#include <security-server.h>
-
-IMPLEMENT_SAFE_SINGLETON(SecurityServer::Log::LogSystem);
-
-namespace {
-
-const int POLL_TIMEOUT = 1000;
-
-void securityClientEnableLogSystem(void) {
-    SecurityServer::Singleton<SecurityServer::Log::LogSystem>::Instance().SetTag("SECURITY_SERVER_CLIENT");
-}
-
-int waitForSocket(int sock, int event, int timeout) {
-    int retval;
-    pollfd desc[1];
-    desc[0].fd = sock;
-    desc[0].events = event;
-
-    while((-1 == (retval = poll(desc, 1, timeout))) && (errno == EINTR)) {
-        timeout >>= 1;
-        errno = 0;
-    }
-
-    if (0 == retval) {
-        LogDebug("Poll timeout");
-    } else if (-1 == retval) {
-        int err = errno;
-        LogError("Error in poll: " << strerror(err));
-    }
-    return retval;
-}
-
-class SockRAII {
-public:
-    SockRAII()
-      : m_sock(-1)
-    {}
-
-    virtual ~SockRAII() {
-        if (m_sock > -1)
-            close(m_sock);
-    }
-
-    int Connect(char const * const interface) {
-        sockaddr_un clientAddr;
-        int flags;
-
-        if (m_sock != -1) // guard
-            close(m_sock);
-
-        m_sock = socket(AF_UNIX, SOCK_STREAM, 0);
-        if (m_sock < 0) {
-            int err = errno;
-            LogError("Error creating socket: " << strerror(err));
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-
-        if ((flags = fcntl(m_sock, F_GETFL, 0)) < 0 ||
-            fcntl(m_sock, F_SETFL, flags | O_NONBLOCK) < 0)
-        {
-            int err = errno;
-            LogError("Error in fcntl: " << strerror(err));
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-
-        memset(&clientAddr, 0, sizeof(clientAddr));
-
-        clientAddr.sun_family = AF_UNIX;
-
-        if (strlen(interface) >= sizeof(clientAddr.sun_path)) {
-            LogError("Error: interface name " << interface << "is too long. Max len is:" << sizeof(clientAddr.sun_path));
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-
-        strcpy(clientAddr.sun_path, interface);
-
-        LogDebug("ClientAddr.sun_path = " << interface);
-
-        int retval = TEMP_FAILURE_RETRY(connect(m_sock, (struct sockaddr*)&clientAddr, SUN_LEN(&clientAddr)));
-        if ((retval == -1) && (errno == EINPROGRESS)) {
-            if (0 >= waitForSocket(m_sock, POLLIN, POLL_TIMEOUT)) {
-                LogError("Error in waitForSocket.");
-                return SECURITY_SERVER_API_ERROR_SOCKET;
-            }
-            int error = 0;
-            size_t len = sizeof(error);
-            retval = getsockopt(m_sock, SOL_SOCKET, SO_ERROR, &error, &len);
-
-            if (-1 == retval) {
-                int err = errno;
-                LogError("Error in getsockopt: " << strerror(err));
-                return SECURITY_SERVER_API_ERROR_SOCKET;
-            }
-
-            if (error == EACCES) {
-                LogError("Access denied");
-                return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
-            }
-
-            if (error != 0) {
-                LogError("Error in connect: " << strerror(error));
-                return SECURITY_SERVER_API_ERROR_SOCKET;
-            }
-
-            return SECURITY_SERVER_API_SUCCESS;
-        }
-
-        if (-1 == retval) {
-            int err = errno;
-            LogError("Error connecting socket: " << strerror(err));
-            if (err == EACCES)
-                return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    int Get() {
-        return m_sock;
-    }
-
-private:
-    int m_sock;
-};
-
-} // namespace anonymous
-
-namespace SecurityServer {
-
-
-int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv) {
-    int ret;
-    SockRAII sock;
-    ssize_t done = 0;
-    char buffer[2048];
-
-    if (SECURITY_SERVER_API_SUCCESS != (ret = sock.Connect(interface))) {
-        LogError("Error in SockRAII");
-        return ret;
-    }
-
-    while ((send.size() - done) > 0) {
-        if (0 >= waitForSocket(sock.Get(), POLLOUT, POLL_TIMEOUT)) {
-            LogError("Error in poll(POLLOUT)");
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-        ssize_t temp = TEMP_FAILURE_RETRY(write(sock.Get(), &send[done], send.size() - done));
-        if (-1 == temp) {
-            int err = errno;
-            LogError("Error in write: " << strerror(err));
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-        done += temp;
-    }
-
-    do {
-        if (0 >= waitForSocket(sock.Get(), POLLIN, POLL_TIMEOUT)) {
-            LogError("Error in poll(POLLIN)");
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-        ssize_t temp = TEMP_FAILURE_RETRY(read(sock.Get(), buffer, 2048));
-        if (-1 == temp) {
-            int err = errno;
-            LogError("Error in read: " << strerror(err));
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-
-        if (0 == temp) {
-            LogError("Read return 0/Connection closed by server(?)");
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-
-        RawBuffer raw(buffer, buffer+temp);
-        recv.Push(raw);
-    } while(!recv.Ready());
-    return SECURITY_SERVER_API_SUCCESS;
-}
-
-int sendToServerAncData(char const * const interface, const RawBuffer &send, struct msghdr &hdr) {
-    int ret;
-    SockRAII sock;
-    ssize_t done = 0;
-
-    if (SECURITY_SERVER_API_SUCCESS != (ret = sock.Connect(interface))) {
-        LogError("Error in SockRAII");
-        return ret;
-    }
-
-    while ((send.size() - done) > 0) {
-        if (0 >= waitForSocket(sock.Get(), POLLOUT, POLL_TIMEOUT)) {
-            LogError("Error in poll(POLLOUT)");
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-        ssize_t temp = TEMP_FAILURE_RETRY(write(sock.Get(), &send[done], send.size() - done));
-        if (-1 == temp) {
-            int err = errno;
-            LogError("Error in write: " << strerror(err));
-            return SECURITY_SERVER_API_ERROR_SOCKET;
-        }
-        done += temp;
-    }
-
-    if (0 >= waitForSocket(sock.Get(), POLLIN, POLL_TIMEOUT)) {
-        LogError("Error in poll(POLLIN)");
-        return SECURITY_SERVER_API_ERROR_SOCKET;
-    }
-
-    ssize_t temp = TEMP_FAILURE_RETRY(recvmsg(sock.Get(), &hdr, MSG_CMSG_CLOEXEC));
-
-    if (temp < 0) {
-        int err = errno;
-        LogError("Error in recvmsg(): " << strerror(err) << " errno: " << err);
-        return SECURITY_SERVER_API_ERROR_SOCKET;
-    }
-
-    if (0 == temp) {
-        LogError("Read return 0/Connection closed by server(?)");
-        return SECURITY_SERVER_API_ERROR_SOCKET;
-    }
-
-    return SECURITY_SERVER_API_SUCCESS;
-}
-
-int try_catch(const std::function<int()>& func)
-{
-    try {
-        return func();
-    } catch (MessageBuffer::Exception::Base &e) {
-        LogError("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
-    } catch (std::exception &e) {
-        LogError("STD exception " << e.what());
-    } catch (...) {
-        LogError("Unknown exception occured");
-    }
-    return SECURITY_SERVER_API_ERROR_UNKNOWN;
-}
-
-} // namespace SecurityServer
-
-static void init_lib(void) __attribute__ ((constructor));
-static void init_lib(void)
-{
-    securityClientEnableLogSystem();
-}
-
-static void fini_lib(void) __attribute__ ((destructor));
-static void fini_lib(void)
-{
-
-}
-
diff --git a/src/server2/client/client-common.h b/src/server2/client/client-common.h
deleted file mode 100644 (file)
index b24cfe9..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-common.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This file constains implementation of common types
- *              used in security server.
- */
-
-#ifndef _SECURITY_SERVER_CLIENT_
-#define _SECURITY_SERVER_CLIENT_
-
-#include <vector>
-#include <functional>
-
-#include <message-buffer.h>
-
-#ifndef SECURITY_SERVER_API
-#define SECURITY_SERVER_API __attribute__((visibility("default")))
-#endif
-
-extern "C" {
-    struct msghdr;
-}
-
-namespace SecurityServer {
-
-typedef std::vector<unsigned char> RawBuffer;
-
-int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv);
-
-/*
- * sendToServerAncData is special case when we want to receive file descriptor
- * passed by Security Server on behalf of calling process. We can't get it with
- * MessageBuffer.
- *
- * This function should be called _ONLY_ in this particular case.
- *
- */
-int sendToServerAncData(char const * const interface, const RawBuffer &send, struct msghdr &hdr);
-
-/*
- * Decorator function that performs frequently repeated exception handling in
- * SS client API functions. Accepts lambda expression as an argument.
- */
-int try_catch(const std::function<int()>& func);
-
-} // namespace SecuritySever
-
-#endif // _SECURITY_SERVER_CLIENT_
diff --git a/src/server2/client/client-cookie.cpp b/src/server2/client/client-cookie.cpp
deleted file mode 100644 (file)
index ef76a98..0000000
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-cookie.cpp
- * @author      Pawel Polawski (p.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This file contain implementation of cookie functions for getting cookies
- */
-
-
-#include <cstdio>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-
-SECURITY_SERVER_API
-int security_server_get_cookie_size(void)
-{
-    return SecurityServer::COOKIE_SIZE;
-}
-
-SECURITY_SERVER_API
-int security_server_request_cookie(char *cookie, size_t bufferSize)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    std::vector<char> receivedCookie;
-
-    LogDebug("security_server_request_cookie() called");
-
-    return try_catch([&] {
-        //checking parameters
-        if (bufferSize < COOKIE_SIZE) {
-            LogDebug("Buffer for cookie too small");
-            return SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL;
-        }
-        if (cookie == NULL) {
-            LogDebug("Cookie pointer empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        //put data into buffer
-        Serialization::Serialize(send, (int)CookieCall::GET_COOKIE);
-
-        //send buffer to server
-        int retval = sendToServer(SERVICE_SOCKET_COOKIE_GET, send.Pop(), recv);
-        if (retval != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << retval);
-            return retval;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, retval);
-        if (retval != SECURITY_SERVER_API_SUCCESS)
-            return retval;
-
-        Deserialization::Deserialize(recv, receivedCookie);
-        if (receivedCookie.size() != COOKIE_SIZE) {
-            LogDebug("No match in cookie size");
-            return SECURITY_SERVER_API_ERROR_BAD_RESPONSE;
-        }
-
-        memcpy(cookie, &receivedCookie[0], receivedCookie.size());
-        return retval;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_get_cookie_pid(const char *cookie)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    int pid;
-    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
-    LogDebug("security_server_get_cookie_pid() called");
-
-    if (cookie == NULL)
-        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-    //preprae cookie to send
-    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
-    return try_catch([&] {
-        //put data into buffer
-        Serialization::Serialize(send, (int)CookieCall::CHECK_PID);
-        Serialization::Serialize(send, key);
-
-        //send buffer to server
-        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
-        if (retval != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << retval);
-            return retval;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, retval);
-        if (retval != SECURITY_SERVER_API_SUCCESS)
-            return retval;
-
-        Deserialization::Deserialize(recv, pid);
-        return pid;
-    });
-}
-
-SECURITY_SERVER_API
-char * security_server_get_smacklabel_cookie(const char *cookie)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-    std::string label;
-
-    LogDebug("security_server_get_smacklabel_cookie() called");
-
-    if (cookie == NULL)
-        return NULL;
-
-    //preprae cookie to send
-    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
-    try {
-        //put data into buffer
-        Serialization::Serialize(send, (int)CookieCall::CHECK_SMACKLABEL);
-        Serialization::Serialize(send, key);
-
-        //send buffer to server
-        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
-        if (retval != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << retval);
-            return NULL;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, retval);
-        if (retval != SECURITY_SERVER_API_SUCCESS)
-            return NULL;
-
-        Deserialization::Deserialize(recv, label);
-
-        return strdup(label.c_str());
-
-    } catch (MessageBuffer::Exception::Base &e) {
-        LogDebug("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
-    } catch (std::exception &e) {
-        LogDebug("STD exception " << e.what());
-    } catch (...) {
-        LogDebug("Unknown exception occured");
-    }
-
-    return NULL;
-}
-
-SECURITY_SERVER_API
-int security_server_check_privilege(const char *cookie, gid_t privilege)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
-    LogDebug("security_server_check_privilege() called");
-
-    if (cookie == NULL)
-        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-    //preprae cookie to send
-    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
-    return try_catch([&] {
-        //put data into buffer
-        Serialization::Serialize(send, (int)CookieCall::CHECK_PRIVILEGE_GID);
-        Serialization::Serialize(send, key);
-        Serialization::Serialize(send, (int)privilege);
-
-        //send buffer to server
-        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
-        if (retval != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << retval);
-            return retval;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, retval);
-        return retval;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_check_privilege_by_cookie(const char *cookie, const char *object, const char *access_rights)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
-    LogDebug("security_server_check_privilege_by_cookie() called");
-
-    if ((cookie == NULL) || (object == NULL) || (access_rights == NULL))
-        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-    //preprae cookie to send
-    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
-    std::string obj(object);
-    std::string access(access_rights);
-
-    return try_catch([&] {
-        //put data into buffer
-        Serialization::Serialize(send, (int)CookieCall::CHECK_PRIVILEGE);
-        Serialization::Serialize(send, key);
-        Serialization::Serialize(send, obj);
-        Serialization::Serialize(send, access);
-
-        //send buffer to server
-        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK, send.Pop(), recv);
-        if (retval != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << retval);
-            return retval;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, retval);
-        return retval;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_get_uid_by_cookie(const char *cookie, uid_t *uid)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
-    LogDebug("security_server_get_uid_by_cookie() called");
-
-    if ((cookie == NULL) || (uid == NULL))
-        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-    //preprae cookie to send
-    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
-    return try_catch([&] {
-        //put data into buffer
-        Serialization::Serialize(send, (int)CookieCall::CHECK_UID);
-        Serialization::Serialize(send, key);
-
-        //send buffer to server
-        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK_TMP, send.Pop(), recv);
-        if (retval != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << retval);
-            return retval;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, retval);
-        if (retval == SECURITY_SERVER_API_SUCCESS) {
-            int tmp;
-            Deserialization::Deserialize(recv, tmp);
-            *uid = static_cast<uid_t>(tmp);
-        }
-
-        return retval;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_get_gid_by_cookie(const char *cookie, gid_t *gid)
-{
-    using namespace SecurityServer;
-    MessageBuffer send, recv;
-    int retval = SECURITY_SERVER_API_ERROR_UNKNOWN;
-
-    LogDebug("security_server_get_uid_by_cookie() called");
-
-    if ((cookie == NULL) || (gid == NULL))
-        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-    //preprae cookie to send
-    std::vector<char> key(cookie, cookie + COOKIE_SIZE);
-
-    return try_catch([&] {
-        //put data into buffer
-        Serialization::Serialize(send, (int)CookieCall::CHECK_GID);
-        Serialization::Serialize(send, key);
-
-        //send buffer to server
-        retval = sendToServer(SERVICE_SOCKET_COOKIE_CHECK_TMP, send.Pop(), recv);
-        if (retval != SECURITY_SERVER_API_SUCCESS) {
-            LogDebug("Error in sendToServer. Error code: " << retval);
-            return retval;
-        }
-
-        //receive response from server
-        Deserialization::Deserialize(recv, retval);
-        if (retval == SECURITY_SERVER_API_SUCCESS) {
-            int tmp;
-            Deserialization::Deserialize(recv, tmp);
-            *gid = static_cast<gid_t>(tmp);
-        }
-
-        return retval;
-    });
-}
-
diff --git a/src/server2/client/client-get-gid.cpp b/src/server2/client/client-get-gid.cpp
deleted file mode 100644 (file)
index e39a1eb..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-get-gid.cpp
- * @author      Jan Olszak (j.olszak@samsung.com)
- * @version     1.0
- * @brief       This file constains implementation of get GID function.
- */
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-SECURITY_SERVER_API
-int security_server_get_gid(const char *objectName) {
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        if (NULL == objectName){
-            LogDebug("Objects name is NULL");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        int objectsNameLen = strlen(objectName);
-        if (0 == objectsNameLen || objectsNameLen > SECURITY_SERVER_MAX_OBJ_NAME){
-            LogDebug("Objects name is empty or too long");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-        Serialization::Serialize(send, std::string(objectName));
-
-        int retCode = sendToServer(
-          SERVICE_SOCKET_GET_GID,
-          send.Pop(),
-          recv);
-
-        if (retCode != SECURITY_SERVER_API_SUCCESS)
-            return retCode;
-
-        Deserialization::Deserialize(recv, retCode);
-
-        // Return if errors
-        if (retCode < 0)
-            return retCode;
-
-        // No errors, return gid
-        gid_t gid;
-        Deserialization::Deserialize(recv, gid);
-        return static_cast<int>(gid);
-    });
-}
-
diff --git a/src/server2/client/client-get-object-name.cpp b/src/server2/client/client-get-object-name.cpp
deleted file mode 100644 (file)
index a9d57ef..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-get-object-name.cpp
- * @author      Jan Olszak (j.olszak@samsung.com)
- * @version     1.0
- * @brief       This file constains implementation of get NAME function.
- */
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-SECURITY_SERVER_API
-int security_server_get_object_name(gid_t gid, char *pObjectName, size_t maxObjectSize)
- {
-    using namespace SecurityServer;
-    return try_catch([&] {
-        if (pObjectName == NULL){
-            LogDebug("Objects name is NULL or empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-        Serialization::Serialize(send, gid);
-
-        int result = sendToServer(
-          SERVICE_SOCKET_GET_OBJECT_NAME,
-          send.Pop(),
-          recv);
-
-
-        if (result != SECURITY_SERVER_API_SUCCESS)
-            return result;
-
-        Deserialization::Deserialize(recv, result);
-
-        std::string retObjectName;
-        Deserialization::Deserialize(recv, retObjectName);
-
-        if(retObjectName.size() > maxObjectSize){
-            LogError("Objects name is too big. Need more space in pObjectName buffer.");
-            return SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL;
-        }
-
-        strcpy(pObjectName,retObjectName.c_str());
-
-        return result;
-
-    });
-}
-
diff --git a/src/server2/client/client-open-for.cpp b/src/server2/client/client-open-for.cpp
deleted file mode 100644 (file)
index d67b2f1..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-open-for-cookie.cpp
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @version     1.0
- * @brief       This file contains implementation of security-server API
- *              for file opening.
- */
-
-#include <cstring>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-SECURITY_SERVER_API
-int security_server_open_for(const char *filename, int *fd)
-{
-   using namespace SecurityServer;
-    try {
-        if (NULL == filename || std::string(filename).empty()) {
-            LogError("Error input param.");
-            return SECURITY_SERVER_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send;
-
-        Serialization::Serialize(send, std::string(filename));
-
-        struct msghdr hdr;
-        struct iovec iov;
-        struct cmsghdr *cmsg = NULL;
-        int retcode = -1;
-        int result = -1;
-        unsigned char cmsgbuf[CMSG_SPACE(sizeof(int))];
-
-        memset(&hdr, 0, sizeof(struct msghdr));
-        memset(cmsgbuf, 0, CMSG_SPACE(sizeof(int)));
-
-        iov.iov_base = &retcode;
-        iov.iov_len = sizeof(retcode);
-        hdr.msg_iov = &iov;
-        hdr.msg_iovlen = 1;
-
-        hdr.msg_control = cmsgbuf;
-        hdr.msg_controllen = CMSG_SPACE(sizeof(int));
-
-        result = sendToServerAncData(SERVICE_SOCKET_OPEN_FOR, send.Pop(), hdr);
-        if (result != SECURITY_SERVER_API_SUCCESS) {
-            *fd = -1;
-            return result;
-        }
-
-        if ((hdr.msg_flags & MSG_CTRUNC) == MSG_CTRUNC) {
-            LogError("Not enough space for ancillary element array.");
-            *fd = -1;
-            return SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL;
-        }
-
-        for(cmsg = CMSG_FIRSTHDR(&hdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&hdr, cmsg)) {
-            if((SOL_SOCKET == cmsg->cmsg_level) && (SCM_RIGHTS == cmsg->cmsg_type)) {
-                memmove(fd, CMSG_DATA(cmsg), sizeof(int));
-            }
-        }
-
-        return retcode;
-    } catch (MessageBuffer::Exception::Base &e) {
-        LogDebug("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
-    } catch (std::exception &e) {
-        LogDebug("STD exception " << e.what());
-    } catch (...) {
-        LogDebug("Unknown exception occured");
-    }
-    return SECURITY_SERVER_API_ERROR_UNKNOWN;
-}
diff --git a/src/server2/client/client-password.cpp b/src/server2/client/client-password.cpp
deleted file mode 100644 (file)
index 3ef4038..0000000
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-password.cpp
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       This file contains implementation of password functions.
- */
-
-#include <cstring>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-inline bool isPasswordIncorrect(const char* pwd)
-{
-    return (pwd == NULL || strlen(pwd) == 0 || strlen(pwd) > SecurityServer::MAX_PASSWORD_LEN);
-}
-
-SECURITY_SERVER_API
-int security_server_is_pwd_valid(unsigned int *current_attempts,
-                                 unsigned int *max_attempts,
-                                 unsigned int *valid_secs)
-{
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        if (NULL == current_attempts || NULL == max_attempts ||
-            NULL == valid_secs) {
-
-            LogError("Wrong input param");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-
-        *current_attempts = 0;
-        *max_attempts = 0;
-        *valid_secs = 0;
-
-        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_IS_PWD_VALID));
-
-        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
-        if (SECURITY_SERVER_API_SUCCESS != retCode) {
-            LogDebug("Error in sendToServer. Error code: " << retCode);
-            return retCode;
-        }
-
-        Deserialization::Deserialize(recv, retCode);
-
-        if(retCode == SECURITY_SERVER_API_ERROR_PASSWORD_EXIST) {
-            Deserialization::Deserialize(recv, *current_attempts);
-            Deserialization::Deserialize(recv, *max_attempts);
-            Deserialization::Deserialize(recv, *valid_secs);
-        }
-
-        return retCode;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_chk_pwd(const char *challenge,
-                            unsigned int *current_attempts,
-                            unsigned int *max_attempts,
-                            unsigned int *valid_secs)
-{
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        if (current_attempts == NULL || max_attempts == NULL || valid_secs == NULL ||
-            isPasswordIncorrect(challenge)) {
-            LogError("Wrong input param");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-
-        *current_attempts = 0;
-        *max_attempts = 0;
-        *valid_secs = 0;
-
-        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PWD));
-        Serialization::Serialize(send, std::string(challenge));
-
-        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
-        if (SECURITY_SERVER_API_SUCCESS != retCode) {
-            LogDebug("Error in sendToServer. Error code: " << retCode);
-            return retCode;
-        }
-
-        Deserialization::Deserialize(recv, retCode);
-
-        switch (retCode) {
-        case SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH:
-        case SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
-        case SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED:
-        case SECURITY_SERVER_API_SUCCESS:
-            Deserialization::Deserialize(recv, *current_attempts);
-            Deserialization::Deserialize(recv, *max_attempts);
-            Deserialization::Deserialize(recv, *valid_secs);
-            break;
-        default:
-            break;
-        }
-
-        return retCode;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_set_pwd(const char *cur_pwd,
-                            const char *new_pwd,
-                            const unsigned int max_challenge,
-                            const unsigned int valid_period_in_days)
-{
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        if (NULL == cur_pwd)
-            cur_pwd = "";
-
-        if (isPasswordIncorrect(new_pwd) || strlen(cur_pwd) > MAX_PASSWORD_LEN) {
-            LogError("Wrong input param.");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-
-        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD));
-        Serialization::Serialize(send, std::string(cur_pwd));
-        Serialization::Serialize(send, std::string(new_pwd));
-        Serialization::Serialize(send, max_challenge);
-        Serialization::Serialize(send, valid_period_in_days);
-
-        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
-        if (SECURITY_SERVER_API_SUCCESS != retCode) {
-            LogError("Error in sendToServer. Error code: " << retCode);
-            return retCode;
-        }
-
-        Deserialization::Deserialize(recv, retCode);
-
-        return retCode;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_set_pwd_validity(const unsigned int valid_period_in_days)
-{
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        MessageBuffer send, recv;
-
-        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_VALIDITY));
-        Serialization::Serialize(send, valid_period_in_days);
-
-        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
-        if (SECURITY_SERVER_API_SUCCESS != retCode) {
-            LogError("Error in sendToServer. Error code: " << retCode);
-            return retCode;
-        }
-
-        Deserialization::Deserialize(recv, retCode);
-
-        return retCode;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_set_pwd_max_challenge(const unsigned int max_challenge)
-{
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        MessageBuffer send, recv;
-
-        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_MAX_CHALLENGE));
-        Serialization::Serialize(send, max_challenge);
-
-        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
-        if (SECURITY_SERVER_API_SUCCESS != retCode) {
-            LogError("Error in sendToServer. Error code: " << retCode);
-            return retCode;
-        }
-
-        Deserialization::Deserialize(recv, retCode);
-
-        return retCode;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_reset_pwd(const char *new_pwd,
-                              const unsigned int max_challenge,
-                              const unsigned int valid_period_in_days)
-{
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        if (isPasswordIncorrect(new_pwd)) {
-            LogError("Wrong input param.");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-
-        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_RST_PWD));
-        Serialization::Serialize(send, std::string(new_pwd));
-        Serialization::Serialize(send, max_challenge);
-        Serialization::Serialize(send, valid_period_in_days);
-
-        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
-        if (SECURITY_SERVER_API_SUCCESS != retCode) {
-            LogError("Error in sendToServer. Error code: " << retCode);
-            return retCode;
-        }
-
-        Deserialization::Deserialize(recv, retCode);
-
-        return retCode;
-    });
-}
-
-SECURITY_SERVER_API
-int security_server_set_pwd_history(int history_size)
-{
-    using namespace SecurityServer;
-
-    return try_catch([&] {
-        if (history_size > static_cast<int>(MAX_PASSWORD_HISTORY) || history_size < 0) {
-            LogError("Wrong input param.");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-
-        Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PWD_HISTORY));
-        Serialization::Serialize(send, static_cast<unsigned int>(history_size));
-
-        int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
-        if (SECURITY_SERVER_API_SUCCESS != retCode) {
-            LogError("Error in sendToServer. Error code: " << retCode);
-            return retCode;
-        }
-
-        Deserialization::Deserialize(recv, retCode);
-
-        return retCode;
-    });
-}
diff --git a/src/server2/client/client-privilege-by-pid.cpp b/src/server2/client/client-privilege-by-pid.cpp
deleted file mode 100644 (file)
index 5447e34..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-check-privilege-by-pid.cpp
- * @author      Jan Cybulski (j.cybulski@samsung.com)
- * @version     1.0
- * @brief       This file constains implementation of security-server API for
- * checking privilege by process id.
- */
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-#include <smack-check.h>
-#include <signal.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-SECURITY_SERVER_API
-int security_server_check_privilege_by_pid(
-        int pid,
-        const char *object,
-        const char *access_rights) {
-    using namespace SecurityServer;
-    return try_catch([&] {
-        if (1 != smack_check())
-            return SECURITY_SERVER_API_SUCCESS;
-
-        // Checking whether a process with pid exists
-        if ((pid < 0) || ((kill(pid, 0) == -1) && (errno == ESRCH))) {
-            LogDebug("pid is invalid, process: " << pid << " does not exist");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        if (NULL == object || 0 == strlen(object)) {
-            LogDebug("object param is NULL or empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        if (NULL == access_rights || 0 == strlen(access_rights)) {
-            LogDebug("access_right param is NULL or empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-        Serialization::Serialize(send, pid);
-        Serialization::Serialize(send, std::string(object));
-        Serialization::Serialize(send, std::string(access_rights));
-
-        int result = sendToServer(
-          SERVICE_SOCKET_PRIVILEGE_BY_PID,
-          send.Pop(),
-          recv);
-
-        if (result != SECURITY_SERVER_API_SUCCESS)
-            return result;
-
-        Deserialization::Deserialize(recv, result);
-        return result;
-    });
-}
-
diff --git a/src/server2/client/client-shared-memory.cpp b/src/server2/client/client-shared-memory.cpp
deleted file mode 100644 (file)
index f688dcd..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-shared-memory.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This file constains implementation of shared memory api.
- */
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-#include <smack-check.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-SECURITY_SERVER_API
-int security_server_app_give_access(const char *customer_label, int customer_pid) {
-    using namespace SecurityServer;
-    return try_catch([&] {
-        if (1 != smack_check())
-            return SECURITY_SERVER_API_SUCCESS;
-
-        if (NULL == customer_label || 0 == strlen(customer_label))
-        {
-            LogDebug("customer_label is NULL or empty");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        MessageBuffer send, recv;
-        Serialization::Serialize(send, std::string(customer_label));
-        Serialization::Serialize(send, customer_pid);
-
-        int result = sendToServer(
-          SERVICE_SOCKET_SHARED_MEMORY,
-          send.Pop(),
-          recv);
-
-        if (result != SECURITY_SERVER_API_SUCCESS)
-            return result;
-
-        Deserialization::Deserialize(recv, result);
-        return result;
-    });
-}
-
diff --git a/src/server2/client/client-socket-privilege.cpp b/src/server2/client/client-socket-privilege.cpp
deleted file mode 100644 (file)
index 61addc3..0000000
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        client-socket-privilege.cpp
- * @author      Zofia Abramowska (z.abramowska@samsung.com)
- * @version     1.0
- * @brief       This file constains implementation of socket privilege api.
- */
-#include <memory>
-
-#include <sys/socket.h>
-#include <sys/smack.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-
-#include <message-buffer.h>
-#include <client-common.h>
-#include <protocols.h>
-#include <smack-check.h>
-
-#include <security-server.h>
-#include <security-server-common.h>
-
-//static int get_exec_path(pid_t pid, std::string &exe)
-//{
-//    using namespace SecurityServer;
-//
-//    try{
-//        MessageBuffer send, recv;
-//        Serialization::Serialize(send, pid);
-//
-//        int result = sendToServer(
-//                SERVICE_SOCKET_EXEC_PATH,
-//                send.Pop(),
-//                recv);
-//        if(result != SECURITY_SERVER_API_SUCCESS)
-//            return result;
-//
-//        Deserialization::Deserialize(recv, result);
-//        if(result != SECURITY_SERVER_API_SUCCESS)
-//            return result;
-//
-//        Deserialization::Deserialize(recv, exe);
-//        return result;
-//    } catch (MessageBuffer::Exception::Base &e) {
-//        LogDebug("SecurityServer::MessageBuffer::Exception " << e.DumpToString());
-//    } catch (std::exception &e) {
-//        LogDebug("STD exception " << e.what());
-//    } catch (...) {
-//        LogDebug("Unknown exception occured");
-//    }
-//    return SECURITY_SERVER_API_ERROR_UNKNOWN;
-//}
-
-SECURITY_SERVER_API
-int security_server_check_privilege_by_sockfd(int sockfd,
-                                              const char *object,
-                                              const char *access_rights)
-{
-    char *subject = NULL;
-    int ret;
-    std::string path;
-    std::unique_ptr<char, void (*)(void*)throw ()> subjectPtr(NULL, std::free);
-
-    //for get socket options
-    struct ucred cr;
-    size_t len = sizeof(struct ucred);
-
-    //SMACK runtime check
-    if (!smack_runtime_check())
-    {
-        LogDebug("No SMACK support on device");
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    if (sockfd < 0 || !object || !access_rights)
-        return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-    ret = smack_new_label_from_socket(sockfd, &subject);
-    if (ret >= 0) {
-        subjectPtr.reset(subject);
-        subject = NULL;
-    } else {
-        LogError("Failed to get new label from socket. Object="
-            << object << ", access=" << access_rights
-            << ", error=" << strerror(errno));
-        return SECURITY_SERVER_API_ERROR_SOCKET;
-    }
-
-    ret = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
-    if (ret < 0) {
-        LogError("Error in getsockopt(). Errno: "
-            << strerror(errno) <<  ", subject="
-            << (subjectPtr.get() ? subjectPtr.get() : "NULL")
-            << ", object=" << object << ", access=" << access_rights
-            << ", error=" << strerror(errno));
-        return SECURITY_SERVER_API_ERROR_SOCKET;
-    }
-
-    ret = security_server_check_privilege_by_pid(cr.pid, object, access_rights);
-
-    //Getting path for logs
-//    if (SECURITY_SERVER_API_SUCCESS != get_exec_path(cr.pid, path)) {
-//        LogError("Failed to read executable path for process " << cr.pid);
-//    }
-//
-//    if (ret == SECURITY_SERVER_API_SUCCESS)
-//        LogSecureDebug("SS_SMACK: caller_pid=" << cr.pid << ", subject=" <<
-//            (subjectPtr.get() ? subjectPtr.get() : "NULL") << ", object=" <<
-//            object << ", access=" << access_rights << ", result=" <<
-//            ret << ", caller_path=" << path.c_str());
-//    else
-//        LogSecureWarning("SS_SMACK: caller_pid=" << cr.pid << ", subject=" <<
-//            (subjectPtr.get() ? subjectPtr.get() : "NULL") << ", object=" <<
-//            object << ", access=" << access_rights << ", result=" <<
-//            ret << ", caller_path=" << path.c_str());
-
-    return ret;
-}
-
-SECURITY_SERVER_API
-char *security_server_get_smacklabel_sockfd(int fd)
-{
-    char *label = NULL;
-
-    if (!smack_check())
-    {
-        LogDebug("No SMACK support on device");
-        label = (char*) malloc(1);
-        if (label) label[0] = '\0';
-        return label;
-    }
-
-    if (smack_new_label_from_socket(fd, &label) < 0)
-    {
-        LogError("Client ERROR: Unable to get socket SMACK label");
-        return NULL;
-    }
-
-    return label;
-}
diff --git a/src/server2/common/connection-info.h b/src/server2/common/connection-info.h
deleted file mode 100644 (file)
index 946b5c8..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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-info.h
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Definition of ConnectionInfo structure and ConnectionInfoMap type.
- */
-
-#ifndef _CONNECTION_INFO_H_
-#define _CONNECTION_INFO_H_
-
-#include <map>
-#include <generic-socket-manager.h>
-#include <message-buffer.h>
-
-namespace SecurityServer
-{
-    struct ConnectionInfo {
-        InterfaceID interfaceID;
-        MessageBuffer buffer;
-    };
-
-    typedef std::map<int, ConnectionInfo> ConnectionInfoMap;
-} //namespace SecurityServer
-
-#endif //_CONNECTION_INFO_H_
diff --git a/src/server2/common/message-buffer.cpp b/src/server2/common/message-buffer.cpp
deleted file mode 100644 (file)
index 3fc090b..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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)
- * @version     1.0
- * @brief       Implementation of MessageBuffer.
- */
-
-#include <message-buffer.h>
-
-#include <dpl/log/log.h>
-
-namespace SecurityServer {
-
-void MessageBuffer::Push(const RawBuffer &data) {
-    m_buffer.AppendCopy(&data[0], data.size());
-}
-
-RawBuffer MessageBuffer::Pop() {
-    size_t size = m_buffer.Size();
-    RawBuffer buffer;
-    buffer.resize(size + sizeof(size_t));
-    memcpy(&buffer[0], &size, sizeof(size_t));
-    m_buffer.FlattenConsume(&buffer[sizeof(size_t)], size);
-    return buffer;
-}
-
-bool MessageBuffer::Ready() {
-    CountBytesLeft();
-    if (m_bytesLeft == 0)
-        return false;
-    if (m_bytesLeft > m_buffer.Size())
-        return false;
-    return true;
-}
-
-void MessageBuffer::Read(size_t num, void *bytes) {
-    CountBytesLeft();
-    if (num > m_bytesLeft) {
-        LogDebug("Protocol broken. OutOfData. Asked for: " << num << " Ready: " << m_bytesLeft << " Buffer.size(): " << m_buffer.Size());
-        Throw(Exception::OutOfData);
-    }
-
-    m_buffer.FlattenConsume(bytes, num);
-    m_bytesLeft -= num;
-}
-
-void MessageBuffer::Write(size_t num, const void *bytes) {
-    m_buffer.AppendCopy(bytes, num);
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/common/message-buffer.h b/src/server2/common/message-buffer.h
deleted file mode 100644 (file)
index 850c7de..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        secket-buffer.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementatin of MessageBuffer.
- */
-
-#ifndef _SECURITY_SERVER_SOCKET_BUFFER_
-#define _SECURITY_SERVER_SOCKET_BUFFER_
-
-#include <vector>
-
-#include <dpl/binary_queue.h>
-#include <dpl/exception.h>
-#include <dpl/serialization.h>
-
-namespace SecurityServer {
-
-typedef std::vector<unsigned char> RawBuffer;
-
-class MessageBuffer : public SecurityServer::IStream {
-public:
-    class Exception
-    {
-    public:
-        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
-        DECLARE_EXCEPTION_TYPE(Base, OutOfData)
-    };
-
-    MessageBuffer()
-      : m_bytesLeft(0)
-    {}
-
-    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);
-
-protected:
-
-    inline void CountBytesLeft() {
-        if (m_bytesLeft > 0)
-            return;  // we already counted m_bytesLeft nothing to do
-
-        if (m_buffer.Size() < sizeof(size_t))
-            return;  // we cannot count m_bytesLeft because buffer is too small
-
-        m_buffer.FlattenConsume(&m_bytesLeft, sizeof(size_t));
-    }
-
-    size_t m_bytesLeft;
-    SecurityServer::BinaryQueue m_buffer;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_SOCKET_BUFFER_
diff --git a/src/server2/common/protocols.cpp b/src/server2/common/protocols.cpp
deleted file mode 100644 (file)
index 4127afc..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        protocols.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       List of all protocols supported by security server.
- */
-
-#include <protocols.h>
-#include <cstddef>
-
-namespace SecurityServer {
-
-char const * const SERVICE_SOCKET_SHARED_MEMORY =
-    "/tmp/.security-server-api-data-share.sock";
-char const * const SERVICE_SOCKET_ECHO =
-    "/tmp/security-server-api-echo.sock";
-char const * const SERVICE_SOCKET_GET_GID =
-    "/tmp/.security-server-api-get-gid.sock";
-char const * const SERVICE_SOCKET_PRIVILEGE_BY_PID =
-    "/tmp/.security-server-api-privilege-by-pid.sock";
-char const * const SERVICE_SOCKET_GET_OBJECT_NAME =
-    "/tmp/.security-server-api-get-object-name.sock";
-char const * const SERVICE_SOCKET_APP_PERMISSIONS =
-    "/tmp/.security-server-api-app-permissions.sock";
-char const * const SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME =
-    "/tmp/.security-server-api-app-privilege-by-name.sock";
-char const * const SERVICE_SOCKET_COOKIE_GET =
-    "/tmp/.security-server-api-cookie-get.sock";
-char const * const SERVICE_SOCKET_COOKIE_CHECK =
-    "/tmp/.security-server-api-cookie-check.sock";
-//TODO: Merge bellow socket with the one above. This should be done
-//after security-server-api-cookie-check.sock will be protected by smack and has proper label
-char const * const SERVICE_SOCKET_COOKIE_CHECK_TMP =
-    "/tmp/.security-server-api-cookie-check-tmp.sock";
-char const * const SERVICE_SOCKET_OPEN_FOR =
-    "/tmp/.security-server-api-open-for.sock";
-char const * const SERVICE_SOCKET_PASSWD_CHECK =
-    "/tmp/.security-server-api-passwd-check.sock";
-char const * const SERVICE_SOCKET_PASSWD_SET =
-    "/tmp/.security-server-api-passwd-set.sock";
-
-const size_t COOKIE_SIZE = 20;
-
-const size_t MAX_PASSWORD_LEN = 32;
-const unsigned int MAX_PASSWORD_HISTORY = 50;
-
-} // namespace SecurityServer
-
diff --git a/src/server2/common/protocols.h b/src/server2/common/protocols.h
deleted file mode 100644 (file)
index 2321e76..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        protocols.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This file contains list of all protocols suported by security-sever.
- */
-
-#ifndef _SECURITY_SERVER_PROTOCOLS_
-#define _SECURITY_SERVER_PROTOCOLS_
-
-#include <cstddef>
-
-namespace SecurityServer {
-
-extern char const * const SERVICE_SOCKET_SHARED_MEMORY;
-extern char const * const SERVICE_SOCKET_ECHO;
-extern char const * const SERVICE_SOCKET_GET_GID;
-extern char const * const SERVICE_SOCKET_PRIVILEGE_BY_PID;
-extern char const * const SERVICE_SOCKET_GET_OBJECT_NAME;
-extern char const * const SERVICE_SOCKET_APP_PERMISSIONS;
-extern char const * const SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME;
-extern char const * const SERVICE_SOCKET_COOKIE_GET;
-extern char const * const SERVICE_SOCKET_COOKIE_CHECK;
-extern char const * const SERVICE_SOCKET_COOKIE_CHECK_TMP;
-extern char const * const SERVICE_SOCKET_OPEN_FOR;
-extern char const * const SERVICE_SOCKET_PASSWD_CHECK;
-extern char const * const SERVICE_SOCKET_PASSWD_SET;
-
-enum class AppPermissionsAction { ENABLE, DISABLE };
-
-enum class CookieCall
-{
-    GET_COOKIE,
-    CHECK_PID,
-    CHECK_SMACKLABEL,
-    CHECK_PRIVILEGE_GID,
-    CHECK_PRIVILEGE,
-    CHECK_GID,
-    CHECK_UID
-};
-
-enum class PrivilegeCheckHdrs
-{
-    CHECK_GIVEN_APP,
-    CHECK_CALLER_APP
-};
-
-extern const size_t COOKIE_SIZE;
-
-enum class PasswordHdrs
-{
-    HDR_IS_PWD_VALID,
-    HDR_CHK_PWD,
-    HDR_SET_PWD,
-    HDR_SET_PWD_VALIDITY,
-    HDR_SET_PWD_MAX_CHALLENGE,
-    HDR_RST_PWD,
-    HDR_SET_PWD_HISTORY
-};
-
-extern const size_t MAX_PASSWORD_LEN;
-extern const unsigned int MAX_PASSWORD_HISTORY;
-
-} // namespace SecuritySever
-
-#endif // _SECURITY_SERVER_PROTOCOLS_
-
diff --git a/src/server2/dpl/core/include/dpl/assert.h b/src/server2/dpl/core/include/dpl/assert.h
deleted file mode 100644 (file)
index a71704d..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2011 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        assert.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of assert
- */
-#ifndef SECURITY_SERVER_ASSERT_H
-#define SECURITY_SERVER_ASSERT_H
-
-#include <dpl/noreturn.h>
-
-namespace SecurityServer {
-// Assertion handler procedure
-// Do not call directly
-// Always use Assert macro
-SECURITYSERVER_NORETURN void AssertProc(const char *condition,
-                             const char *file,
-                             int line,
-                             const char *function);
-} // namespace SecurityServer
-
-#define Assert(Condition) do { if (!(Condition)) { SecurityServer::AssertProc(#Condition, \
-                                                                   __FILE__, \
-                                                                   __LINE__, \
-                                                                   __FUNCTION__); \
-                               } } while (0)
-
-#endif // SECURITY_SERVER_ASSERT_H
diff --git a/src/server2/dpl/core/include/dpl/binary_queue.h b/src/server2/dpl/core/include/dpl/binary_queue.h
deleted file mode 100644 (file)
index 387a71a..0000000
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (c) 2011 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
- */
-#ifndef SECURITY_SERVER_BINARY_QUEUE_H
-#define SECURITY_SERVER_BINARY_QUEUE_H
-
-//#include <dpl/abstract_input_output.h>
-#include <dpl/exception.h>
-#include <dpl/noncopyable.h>
-#include <memory>
-#include <list>
-
-namespace SecurityServer {
-/**
- * Binary queue auto pointer
- */
-class BinaryQueue;
-typedef std::auto_ptr<BinaryQueue> BinaryQueueAutoPtr;
-
-/**
- * Binary stream implemented as constant size bucket list
- *
- * @todo Add optimized implementation for FlattenConsume
- */
-class BinaryQueue
-//  : public AbstractInputOutput
-{
-  public:
-    class Exception
-    {
-      public:
-        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
-        DECLARE_EXCEPTION_TYPE(Base, OutOfData)
-    };
-
-    typedef void (*BufferDeleter)(const void *buffer, size_t bufferSize,
-                                  void *userParam);
-    static void BufferDeleterFree(const void *buffer,
-                                  size_t bufferSize,
-                                  void *userParam);
-
-    class BucketVisitor
-    {
-      public:
-        /**
-         * Destructor
-         */
-        virtual ~BucketVisitor();
-
-        /**
-         * Visit bucket
-         *
-         * @return none
-         * @param[in] buffer Constant pointer to bucket data buffer
-         * @param[in] bufferSize Number of bytes in bucket
-         */
-        virtual void OnVisitBucket(const void *buffer, size_t bufferSize) = 0;
-    };
-
-  private:
-    struct Bucket :
-        private Noncopyable
-    {
-        const void *buffer;
-        const void *ptr;
-        size_t size;
-        size_t left;
-
-        BufferDeleter deleter;
-        void *param;
-
-        Bucket(const void *buffer,
-               size_t bufferSize,
-               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);
-
-    /**
-     * 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);
-
-    /**
-     * Append copy of @a bufferSize 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] bufferSize 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 bufferSize);
-
-    /**
-     * Append @a bufferSize 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] bufferSize 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 bufferSize,
-        BufferDeleter deleter =
-            &BinaryQueue::BufferDeleterFree,
-        void *userParam = NULL);
-
-    /**
-     * 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 bufferSize 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] bufferSize 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 bufferSize) const;
-
-    /**
-     * Retrieve @a bufferSize 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] bufferSize 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 bufferSize);
-
-    /**
-     * 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;
-
-    /**
-     * IAbstractInput interface
-     */
-    virtual BinaryQueueAutoPtr Read(size_t size);
-
-    /**
-     * IAbstractOutput interface
-     */
-    virtual size_t Write(const BinaryQueue &buffer, size_t bufferSize);
-};
-
-} // namespace SecurityServer
-
-#endif // SECURITY_SERVER_BINARY_QUEUE_H
diff --git a/src/server2/dpl/core/include/dpl/colors.h b/src/server2/dpl/core/include/dpl/colors.h
deleted file mode 100644 (file)
index 37ce940..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2011 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        colors.h
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       Some constants with definition of colors for Console
- *              and html output
- */
-
-#ifndef SECURITY_SERVER_COLORS_H
-#define SECURITY_SERVER_COLORS_H
-
-namespace SecurityServer {
-namespace Colors {
-namespace Text {
-extern const char* BOLD_GREEN_BEGIN;
-extern const char* BOLD_GREEN_END;
-extern const char* PURPLE_BEGIN;
-extern const char* PURPLE_END;
-extern const char* RED_BEGIN;
-extern const char* RED_END;
-extern const char* GREEN_BEGIN;
-extern const char* GREEN_END;
-extern const char* CYAN_BEGIN;
-extern const char* CYAN_END;
-extern const char* BOLD_RED_BEGIN;
-extern const char* BOLD_RED_END;
-extern const char* BOLD_YELLOW_BEGIN;
-extern const char* BOLD_YELLOW_END;
-extern const char* BOLD_GOLD_BEGIN;
-extern const char* BOLD_GOLD_END;
-extern const char* BOLD_WHITE_BEGIN;
-extern const char* BOLD_WHITE_END;
-} //namespace Text
-
-namespace Html {
-extern const char* BOLD_GREEN_BEGIN;
-extern const char* BOLD_GREEN_END;
-extern const char* PURPLE_BEGIN;
-extern const char* PURPLE_END;
-extern const char* RED_BEGIN;
-extern const char* RED_END;
-extern const char* GREEN_BEGIN;
-extern const char* GREEN_END;
-extern const char* CYAN_BEGIN;
-extern const char* CYAN_END;
-extern const char* BOLD_RED_BEGIN;
-extern const char* BOLD_RED_END;
-extern const char* BOLD_YELLOW_BEGIN;
-extern const char* BOLD_YELLOW_END;
-extern const char* BOLD_GOLD_BEGIN;
-extern const char* BOLD_GOLD_END;
-extern const char* BOLD_WHITE_BEGIN;
-extern const char* BOLD_WHITE_END;
-} //namespace Html
-} //namespace Colors
-} //namespace SecurityServer
-
-#endif /* SECURITY_SERVER_COLORS_H */
diff --git a/src/server2/dpl/core/include/dpl/exception.h b/src/server2/dpl/core/include/dpl/exception.h
deleted file mode 100644 (file)
index ff8d300..0000000
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * Copyright (c) 2011 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    exception.h
- * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version 1.0
- * @brief   Header file for base exception
- */
-#ifndef SECURITY_SERVER_EXCEPTION_H
-#define SECURITY_SERVER_EXCEPTION_H
-
-#include <string>
-#include <cstring>
-#include <cstdio>
-#include <exception>
-#include <cstdlib>
-#include <sstream>
-
-namespace SecurityServer {
-void LogUnhandledException(const std::string &str);
-void LogUnhandledException(const std::string &str,
-                           const char *filename,
-                           int line,
-                           const char *function);
-}
-
-namespace SecurityServer {
-class Exception
-{
-  private:
-    static unsigned int m_exceptionCount;
-    static Exception* m_lastException;
-    static void (*m_terminateHandler)();
-
-    static void AddRef(Exception* exception)
-    {
-        if (!m_exceptionCount) {
-            m_terminateHandler = std::set_terminate(&TerminateHandler);
-        }
-
-        ++m_exceptionCount;
-        m_lastException = exception;
-    }
-
-    static void UnRef(Exception* e)
-    {
-        if (m_lastException == e) {
-            m_lastException = NULL;
-        }
-
-        --m_exceptionCount;
-
-        if (!m_exceptionCount) {
-            std::set_terminate(m_terminateHandler);
-            m_terminateHandler = NULL;
-        }
-    }
-
-    static void TerminateHandler()
-    {
-        if (m_lastException != NULL) {
-            DisplayKnownException(*m_lastException);
-            abort();
-        } else {
-            DisplayUnknownException();
-            abort();
-        }
-    }
-
-    Exception *m_reason;
-    std::string m_path;
-    std::string m_function;
-    int m_line;
-
-  protected:
-    std::string m_message;
-    std::string m_className;
-
-  public:
-    static std::string KnownExceptionToString(const Exception &e)
-    {
-        std::ostringstream message;
-        message <<
-        "\033[1;5;31m\n=== Unhandled SecurityServer exception occurred ===\033[m\n\n";
-        message << "\033[1;33mException trace:\033[m\n\n";
-        message << e.DumpToString();
-        message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-
-        return message.str();
-    }
-
-    static std::string UnknownExceptionToString()
-    {
-        std::ostringstream message;
-        message <<
-        "\033[1;5;31m\n=== Unhandled non-SecurityServer exception occurred ===\033[m\n\n";
-        message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-
-        return message.str();
-    }
-
-    static void DisplayKnownException(const Exception& e)
-    {
-        LogUnhandledException(KnownExceptionToString(e).c_str());
-    }
-
-    static void DisplayUnknownException()
-    {
-        LogUnhandledException(UnknownExceptionToString().c_str());
-    }
-
-    Exception(const Exception &other)
-    {
-        // Deep copy
-        if (other.m_reason != NULL) {
-            m_reason = new Exception(*other.m_reason);
-        } else {
-            m_reason = NULL;
-        }
-
-        m_message = other.m_message;
-        m_path = other.m_path;
-        m_function = other.m_function;
-        m_line = other.m_line;
-
-        m_className = other.m_className;
-
-        AddRef(this);
-    }
-
-    const Exception &operator =(const Exception &other)
-    {
-        if (this == &other) {
-            return *this;
-        }
-
-        // Deep copy
-        if (other.m_reason != NULL) {
-            m_reason = new Exception(*other.m_reason);
-        } else {
-            m_reason = NULL;
-        }
-
-        m_message = other.m_message;
-        m_path = other.m_path;
-        m_function = other.m_function;
-        m_line = other.m_line;
-
-        m_className = other.m_className;
-
-        AddRef(this);
-
-        return *this;
-    }
-
-    Exception(const char *path,
-              const char *function,
-              int line,
-              const std::string &message) :
-        m_reason(NULL),
-        m_path(path),
-        m_function(function),
-        m_line(line),
-        m_message(message)
-    {
-        AddRef(this);
-    }
-
-    Exception(const char *path,
-              const char *function,
-              int line,
-              const Exception &reason,
-              const std::string &message) :
-        m_reason(new Exception(reason)),
-        m_path(path),
-        m_function(function),
-        m_line(line),
-        m_message(message)
-    {
-        AddRef(this);
-    }
-
-    virtual ~Exception() throw()
-    {
-        if (m_reason != NULL) {
-            delete m_reason;
-            m_reason = NULL;
-        }
-
-        UnRef(this);
-    }
-
-    void Dump() const
-    {
-        // Show reason first
-        if (m_reason != NULL) {
-            m_reason->Dump();
-        }
-
-        // Afterward, dump exception
-        const char *file = strchr(m_path.c_str(), '/');
-
-        if (file == NULL) {
-            file = m_path.c_str();
-        } else {
-            ++file;
-        }
-
-        printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
-               file, m_line,
-               m_function.c_str(),
-               m_className.c_str(),
-               m_message.empty() ? "<EMPTY>" : m_message.c_str());
-    }
-
-    std::string DumpToString() const
-    {
-        std::string ret;
-        if (m_reason != NULL) {
-            ret = m_reason->DumpToString();
-        }
-
-        const char *file = strchr(m_path.c_str(), '/');
-
-        if (file == NULL) {
-            file = m_path.c_str();
-        } else {
-            ++file;
-        }
-
-        char buf[1024];
-        snprintf(buf,
-                 sizeof(buf),
-                 "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
-                 file,
-                 m_line,
-                 m_function.c_str(),
-                 m_className.c_str(),
-                 m_message.empty() ? "<EMPTY>" : m_message.c_str());
-
-        buf[sizeof(buf) - 1] = '\n';
-        ret += buf;
-
-        return ret;
-    }
-
-    Exception *GetReason() const
-    {
-        return m_reason;
-    }
-
-    std::string GetPath() const
-    {
-        return m_path;
-    }
-
-    std::string GetFunction() const
-    {
-        return m_function;
-    }
-
-    int GetLine() const
-    {
-        return m_line;
-    }
-
-    std::string GetMessage() const
-    {
-        return m_message;
-    }
-
-    std::string GetClassName() const
-    {
-        return m_className;
-    }
-};
-} // namespace SecurityServer
-
-#define Try try
-
-#define Throw(ClassName) \
-    throw ClassName(__FILE__, __FUNCTION__, __LINE__)
-
-#define ThrowMsg(ClassName, Message)                                                 \
-    do                                                                               \
-    {                                                                                \
-        std::ostringstream dplLoggingStream;                                         \
-        dplLoggingStream << Message;                                                 \
-        throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str());   \
-    } while (0)
-
-#define ReThrow(ClassName) \
-    throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
-
-#define ReThrowMsg(ClassName, Message) \
-    throw ClassName(__FILE__, \
-                    __FUNCTION__, \
-                    __LINE__, \
-                    _rethrown_exception, \
-                    Message)
-
-#define Catch(ClassName) \
-    catch (const ClassName &_rethrown_exception)
-
-#define DECLARE_EXCEPTION_TYPE(BaseClass, Class)                                                                                          \
-    class Class :                                                                                                                                 \
-        public BaseClass                                                                                                                \
-    {                                                                                                                                     \
-      public:                                                                                                                               \
-        Class(const char *path, \
-              const char *function, \
-              int line, \
-              const std::string & message = std::string()) :                                                                                                                             \
-            BaseClass(path, function, line, message)                                                                                    \
-        {                                                                                                                                 \
-            BaseClass::m_className = #Class;                                                                                              \
-        }                                                                                                                                 \
-                                                                                                                                          \
-        Class(const char *path, \
-              const char *function, \
-              int line, \
-              const SecurityServer::Exception & reason, \
-              const std::string & message = std::string()) :                                                                                                                             \
-            BaseClass(path, function, line, reason, message)                                                                            \
-        {                                                                                                                                 \
-            BaseClass::m_className = #Class;                                                                                              \
-        }                                                                                                                                 \
-    };
-
-#define UNHANDLED_EXCEPTION_HANDLER_BEGIN try
-
-#define UNHANDLED_EXCEPTION_HANDLER_END                                                                   \
-    catch (const SecurityServer::Exception &exception)                                                               \
-    {                                                                                                     \
-        std::ostringstream msg;                                                                           \
-        msg << SecurityServer::Exception::KnownExceptionToString(exception);                                         \
-        SecurityServer::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
-        abort();                                                                                          \
-    }                                                                                                     \
-    catch (std::exception& e)                                                                             \
-    {                                                                                                     \
-        std::ostringstream msg;                                                                           \
-        msg << e.what();                                                                                  \
-        msg << "\n";                                                                                      \
-        msg << SecurityServer::Exception::UnknownExceptionToString();                                                \
-        SecurityServer::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
-        abort();                                                                                          \
-    }                                                                                                     \
-    catch (...)                                                                                           \
-    {                                                                                                     \
-        std::ostringstream msg;                                                                           \
-        msg << SecurityServer::Exception::UnknownExceptionToString();                                                \
-        SecurityServer::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
-        abort();                                                                                          \
-    }
-
-namespace SecurityServer {
-namespace CommonException {
-/**
- * Internal exception definitions
- *
- * These should normally not happen.
- * Usually, exception trace with internal error includes
- * important messages.
- */
-DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
-                                                 // underlying libraries or
-                                                 // kernel
-}
-}
-
-#endif // SECURITY_SERVER_EXCEPTION_H
diff --git a/src/server2/dpl/core/include/dpl/noncopyable.h b/src/server2/dpl/core/include/dpl/noncopyable.h
deleted file mode 100644 (file)
index dae75e8..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2011 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        noncopyable
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of noncopyable
- */
-#ifndef SECURITYSERVER_NONCOPYABLE_H
-#define SECURITYSERVER_NONCOPYABLE_H
-
-namespace SecurityServer {
-class Noncopyable
-{
-  private:
-    Noncopyable(const Noncopyable &);
-    const Noncopyable &operator=(const Noncopyable &);
-
-  public:
-    Noncopyable();
-    virtual ~Noncopyable();
-};
-} // namespace SecurityServer
-
-#endif // SECURITYSERVER_NONCOPYABLE_H
diff --git a/src/server2/dpl/core/include/dpl/noreturn.h b/src/server2/dpl/core/include/dpl/noreturn.h
deleted file mode 100644 (file)
index 44dfd4a..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2011 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        noreturn.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of noreturn
- */
-#ifndef SECURITYSERVER_NORETURN_H
-#define SECURITYSERVER_NORETURN_H
-
-#define SECURITYSERVER_NORETURN __attribute__((__noreturn__))
-
-#endif // SECURITYSERVER_NORETURN_H
diff --git a/src/server2/dpl/core/include/dpl/serialization.h b/src/server2/dpl/core/include/dpl/serialization.h
deleted file mode 100644 (file)
index 5c2a0ff..0000000
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-#ifndef SERIALIZATION_H
-#define SERIALIZATION_H
-
-#include <string>
-#include <vector>
-#include <list>
-#include <map>
-
-namespace SecurityServer {
-// 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 int
-    static void Serialize(IStream& stream, const unsigned value)
-    {
-        stream.Write(sizeof(value), &value);
-    }
-    static void Serialize(IStream& stream, const unsigned* const value)
-    {
-        stream.Write(sizeof(*value), value);
-    }
-
-    // int
-    static void Serialize(IStream& stream, const int value)
-    {
-        stream.Write(sizeof(value), &value);
-    }
-    static void Serialize(IStream& stream, const int* 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);
-    }
-
-    // time_t
-    static void Serialize(IStream& stream, const time_t value)
-    {
-        stream.Write(sizeof(value), &value);
-    }
-    static void Serialize(IStream& stream, const time_t* const value)
-    {
-        stream.Write(sizeof(*value), value);
-    }
-
-    // std::string
-    static void Serialize(IStream& stream, const std::string& str)
-    {
-        int length = str.size();
-        stream.Write(sizeof(length), &length);
-        stream.Write(length, str.c_str());
-    }
-    static void Serialize(IStream& stream, const std::string* const str)
-    {
-        int length = str->size();
-        stream.Write(sizeof(length), &length);
-        stream.Write(length, str->c_str());
-    }
-
-    // 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);
-    }
-
-    // std::vector
-    template <typename T>
-    static void Serialize(IStream& stream, const std::vector<T>& vec)
-    {
-        int length = vec.size();
-        stream.Write(sizeof(length), &length);
-        for (typename std::vector<T>::const_iterator vec_iter = vec.begin();
-             vec_iter != vec.end(); vec_iter++)
-        {
-            Serialize(stream, *vec_iter);
-        }
-    }
-    template <typename T>
-    static void Serialize(IStream& stream, const std::vector<T>* 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);
-    }
-}; // 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 int
-    static void Deserialize(IStream& stream, unsigned& value)
-    {
-        stream.Read(sizeof(value), &value);
-    }
-    static void Deserialize(IStream& stream, unsigned*& value)
-    {
-        value = new unsigned;
-        stream.Read(sizeof(*value), value);
-    }
-
-    // int
-    static void Deserialize(IStream& stream, int& value)
-    {
-        stream.Read(sizeof(value), &value);
-    }
-    static void Deserialize(IStream& stream, int*& value)
-    {
-        value = new int;
-        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);
-    }
-
-    // time_t
-    static void Deserialize(IStream& stream, time_t& value)
-    {
-        stream.Read(sizeof(value), &value);
-    }
-    static void Deserialize(IStream& stream, time_t*& value)
-    {
-        value = new time_t;
-        stream.Read(sizeof(*value), value);
-    }
-
-    // std::string
-    static void Deserialize(IStream& stream, std::string& str)
-    {
-        int length;
-        stream.Read(sizeof(length), &length);
-        char * buf = new char[length + 1];
-        stream.Read(length, buf);
-        buf[length] = 0;
-        str = std::string(buf);
-        delete[] buf;
-    }
-    static void Deserialize(IStream& stream, std::string*& str)
-    {
-        int length;
-        stream.Read(sizeof(length), &length);
-        char * buf = new char[length + 1];
-        stream.Read(length, buf);
-        buf[length] = 0;
-        str = new std::string(buf);
-        delete[] buf;
-    }
-
-    // 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(obj);
-        }
-    }
-    template <typename T>
-    static void Deserialize(IStream& stream, std::list<T>*& list)
-    {
-        list = new std::list<T>;
-        Deserialize(stream, *list);
-    }
-
-    // std::vector
-    template <typename T>
-    static void Deserialize(IStream& stream, std::vector<T>& vec)
-    {
-        int length;
-        stream.Read(sizeof(length), &length);
-        for (int i = 0; i < length; ++i) {
-            T obj;
-            Deserialize(stream, obj);
-            vec.push_back(obj);
-        }
-    }
-    template <typename T>
-    static void Deserialize(IStream& stream, std::vector<T>*& vec)
-    {
-        vec = new std::vector<T>;
-        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] = 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
-} // namespace SecurityServer
-
-#endif // SERIALIZATION_H
diff --git a/src/server2/dpl/core/include/dpl/singleton.h b/src/server2/dpl/core/include/dpl/singleton.h
deleted file mode 100644 (file)
index b46104f..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2011 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        singleton.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of singleton
- */
-#ifndef SECURITYSERVER_SINGLETON_H
-#define SECURITYSERVER_SINGLETON_H
-
-namespace SecurityServer {
-template<typename Class>
-class Singleton :
-    private Class
-{
-    //
-    // Note:
-    //
-    // To remove posibility of instantiating directly Class,
-    // make Class' default constructor protected
-    //
-
-  private:
-    Singleton()
-    {}
-
-    static Singleton &InternalInstance();
-
-  public:
-    virtual ~Singleton()
-    {}
-
-    static Class &Instance();
-};
-} // namespace SecurityServer
-
-#endif // SECURITYSERVER_SINGLETON_H
diff --git a/src/server2/dpl/core/include/dpl/singleton_impl.h b/src/server2/dpl/core/include/dpl/singleton_impl.h
deleted file mode 100644 (file)
index 31c054f..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2011 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        singleton_impl.h
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of singleton
- */
-#ifndef SECURITYSERVER_SINGLETON_IMPL_H
-#define SECURITYSERVER_SINGLETON_IMPL_H
-
-/*
- * WARNING!
- *
- * If some singleton's implementation uses another singletons implementation,
- * those templates make the second singleton a dubleton. Be warned. Try to use
- * singleton_safe_impl.h if possible.
- */
-
-namespace SecurityServer {
-template<typename Class>
-Singleton<Class>& Singleton<Class>::InternalInstance()
-{
-    static Singleton<Class> instance;
-    return instance;
-}
-
-template<typename Class>
-Class &Singleton<Class>::Instance()
-{
-    Singleton<Class>& instance = Singleton<Class>::InternalInstance();
-    return instance;
-}
-} // namespace SecurityServer
-
-#define IMPLEMENT_SINGLETON(Type)                                           \
-    template SecurityServer::Singleton<Type>&SecurityServer::Singleton<Type>::InternalInstance();    \
-    template Type & SecurityServer::Singleton<Type>::Instance();                            \
-
-#endif // SECURITYSERVER_SINGLETON_IMPL_H
diff --git a/src/server2/dpl/core/include/dpl/singleton_safe_impl.h b/src/server2/dpl/core/include/dpl/singleton_safe_impl.h
deleted file mode 100644 (file)
index abef281..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2011 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        singleton_safe_impl.h
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of singleton
- */
-#ifndef SECURITYSERVER_SINGLETON_SAFE_IMPL_H
-#define SECURITYSERVER_SINGLETON_SAFE_IMPL_H
-
-#define IMPLEMENT_SAFE_SINGLETON(Class)                                        \
-    namespace SecurityServer {                                                                \
-    template<>                                                                     \
-    Singleton<Class>&Singleton<Class>::InternalInstance()                         \
-    {                                                                              \
-        static Singleton<Class> instance;                                          \
-        return instance;                                                           \
-    }                                                                              \
-                                                                               \
-    template<>                                                                     \
-    Class & Singleton<Class>::Instance()                                            \
-    {                                                                              \
-        Singleton<Class>& instance = Singleton<Class>::InternalInstance();         \
-        return instance;                                                           \
-    }                                                                              \
-                                                                               \
-    template Singleton<Class>&Singleton<Class>::InternalInstance();               \
-    template Class & Singleton<Class>::Instance();                                  \
-    } // namespace SecurityServer
-
-#endif // SECURITYSERVER_SINGLETON_SAFE_IMPL_H
diff --git a/src/server2/dpl/core/src/assert.cpp b/src/server2/dpl/core/src/assert.cpp
deleted file mode 100644 (file)
index 440b03a..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (c) 2011 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        assert.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of assert
- */
-#include <stddef.h>
-#include <dpl/assert.h>
-#include <dpl/colors.h>
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-#include <cstdlib>
-
-namespace SecurityServer {
-void AssertProc(const char *condition,
-                const char *file,
-                int line,
-                const char *function)
-{
-#define INTERNAL_LOG(message)                                          \
-    do                                                                 \
-    {                                                                  \
-        std::ostringstream platformLog;                                \
-        platformLog << message;                                        \
-        SecurityServer::Log::LogSystemSingleton::Instance().Pedantic(             \
-            platformLog.str().c_str(),                                 \
-            __FILE__, __LINE__, __FUNCTION__);                         \
-    } \
-    while (0)
-
-    // Try to log failed assertion to log system
-    Try
-    {
-        INTERNAL_LOG(
-            "################################################################################");
-        INTERNAL_LOG(
-            "###                          SecurityServer assertion failed!                           ###");
-        INTERNAL_LOG(
-            "################################################################################");
-        INTERNAL_LOG("### Condition: " << condition);
-        INTERNAL_LOG("### File: " << file);
-        INTERNAL_LOG("### Line: " << line);
-        INTERNAL_LOG("### Function: " << function);
-        INTERNAL_LOG(
-            "################################################################################");
-    } catch (Exception) {
-        // Just ignore possible double errors
-    }
-
-    // Fail with c-library abort
-    abort();
-}
-} // namespace SecurityServer
diff --git a/src/server2/dpl/core/src/binary_queue.cpp b/src/server2/dpl/core/src/binary_queue.cpp
deleted file mode 100644 (file)
index be0c65d..0000000
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
- * Copyright (c) 2011 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       This file is the implementation file of binary queue
- */
-#include <stddef.h>
-#include <dpl/binary_queue.h>
-#include <dpl/assert.h>
-#include <algorithm>
-#include <malloc.h>
-#include <cstring>
-#include <new>
-
-namespace SecurityServer {
-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 == NULL) {
-        throw std::bad_alloc();
-    }
-
-    try {
-        other.Flatten(bufferCopy, other.m_size);
-        AppendUnmanaged(bufferCopy, other.m_size, &BufferDeleterFree, NULL);
-    } 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 bufferSize)
-{
-    // Create data copy with malloc/free
-    void *bufferCopy = malloc(bufferSize);
-
-    // Check if allocation succeded
-    if (bufferCopy == NULL) {
-        throw std::bad_alloc();
-    }
-
-    // Copy user data
-    memcpy(bufferCopy, buffer, bufferSize);
-
-    try {
-        // Try to append new bucket
-        AppendUnmanaged(bufferCopy, bufferSize, &BufferDeleterFree, NULL);
-    } catch (const std::bad_alloc &) {
-        // Free allocated memory
-        free(bufferCopy);
-        throw;
-    }
-}
-
-void BinaryQueue::AppendUnmanaged(const void* buffer,
-                                  size_t bufferSize,
-                                  BufferDeleter deleter,
-                                  void* userParam)
-{
-    // Do not attach empty buckets
-    if (bufferSize == 0) {
-        deleter(buffer, bufferSize, userParam);
-        return;
-    }
-
-    // Just add new bucket with selected deleter
-    Bucket *bucket = new Bucket(buffer, bufferSize, deleter, userParam);
-    try {
-        m_buckets.push_back(bucket);
-    } catch (const std::bad_alloc &) {
-        delete bucket;
-        throw;
-    }
-
-    // Increase total queue size
-    m_size += bufferSize;
-}
-
-size_t BinaryQueue::Size() const
-{
-    return m_size;
-}
-
-bool BinaryQueue::Empty() const
-{
-    return m_size == 0;
-}
-
-void BinaryQueue::Consume(size_t size)
-{
-    // Check parameters
-    if (size > m_size) {
-        Throw(Exception::OutOfData);
-    }
-
-    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 bufferSize) const
-{
-    // Check parameters
-    if (bufferSize == 0) {
-        return;
-    }
-
-    if (bufferSize > m_size) {
-        Throw(Exception::OutOfData);
-    }
-
-    size_t bytesLeft = bufferSize;
-    void *ptr = buffer;
-    BucketList::const_iterator bucketIterator = m_buckets.begin();
-    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 bufferSize)
-{
-    // FIXME: Optimize
-    Flatten(buffer, bufferSize);
-    Consume(bufferSize);
-}
-
-void BinaryQueue::DeleteBucket(BinaryQueue::Bucket *bucket)
-{
-    delete bucket;
-}
-
-void BinaryQueue::BufferDeleterFree(const void* data,
-                                    size_t dataSize,
-                                    void* userParam)
-{
-    (void)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)
-{
-    Assert(data != NULL);
-    Assert(deleter != NULL);
-}
-
-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
-{
-    Assert(visitor != NULL);
-
-    // Visit all buckets
-    std::for_each(m_buckets.begin(), m_buckets.end(), BucketVisitorCall(visitor));
-}
-
-BinaryQueueAutoPtr BinaryQueue::Read(size_t size)
-{
-    // Simulate input stream
-    size_t available = std::min(size, m_size);
-
-    std::unique_ptr<void, std::function<void(void*)>>
-        bufferCopy(malloc(available), free);
-
-    if (!bufferCopy.get()) {
-        throw std::bad_alloc();
-    }
-
-    BinaryQueueAutoPtr result(new BinaryQueue());
-
-    Flatten(bufferCopy.get(), available);
-    result->AppendUnmanaged(
-        bufferCopy.release(), available, &BufferDeleterFree, NULL);
-    Consume(available);
-
-    return result;
-}
-
-size_t BinaryQueue::Write(const BinaryQueue &buffer, size_t bufferSize)
-{
-    // Simulate output stream
-    AppendCopyFrom(buffer);
-    return bufferSize;
-}
-} // namespace SecurityServer
diff --git a/src/server2/dpl/core/src/colors.cpp b/src/server2/dpl/core/src/colors.cpp
deleted file mode 100644 (file)
index 6563a26..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2011 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        colors.cpp
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       Some constants with definition of colors for Console
- *              and html output
- */
-#include <stddef.h>
-#include <dpl/colors.h>
-
-namespace SecurityServer {
-namespace Colors {
-namespace Text {
-const char* BOLD_GREEN_BEGIN = "\033[1;32m";
-const char* BOLD_GREEN_END = "\033[m";
-const char* RED_BEGIN = "\033[0;31m";
-const char* RED_END = "\033[m";
-const char* PURPLE_BEGIN = "\033[0;35m";
-const char* PURPLE_END = "\033[m";
-const char* GREEN_BEGIN = "\033[0;32m";
-const char* GREEN_END = "\033[m";
-const char* CYAN_BEGIN = "\033[0;36m";
-const char* CYAN_END = "\033[m";
-const char* BOLD_RED_BEGIN = "\033[1;31m";
-const char* BOLD_RED_END = "\033[m";
-const char* BOLD_YELLOW_BEGIN = "\033[1;33m";
-const char* BOLD_YELLOW_END = "\033[m";
-const char* BOLD_GOLD_BEGIN = "\033[0;33m";
-const char* BOLD_GOLD_END = "\033[m";
-const char* BOLD_WHITE_BEGIN = "\033[1;37m";
-const char* BOLD_WHITE_END = "\033[m";
-} //namespace Text
-
-namespace Html {
-const char* BOLD_GREEN_BEGIN = "<font color=\"green\"><b>";
-const char* BOLD_GREEN_END = "</b></font>";
-const char* PURPLE_BEGIN = "<font color=\"purple\"><b>";
-const char* PURPLE_END = "</b></font>";
-const char* RED_BEGIN = "<font color=\"red\"><b>";
-const char* RED_END = "</b></font>";
-const char* GREEN_BEGIN = "<font color=\"green\">";
-const char* GREEN_END = "</font>";
-const char* CYAN_BEGIN = "<font color=\"cyan\">";
-const char* CYAN_END = "</font>";
-const char* BOLD_RED_BEGIN = "<font color=\"red\"><b>";
-const char* BOLD_RED_END = "</b></font>";
-const char* BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>";
-const char* BOLD_YELLOW_END = "</b></font>";
-const char* BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>";
-const char* BOLD_GOLD_END = "</b></font>";
-const char* BOLD_WHITE_BEGIN = "<font color=\"white\"><b>";
-const char* BOLD_WHITE_END = "</b></font>";
-} //namespace Html
-} //namespace Colors
-} //namespace SecurityServer
diff --git a/src/server2/dpl/core/src/exception.cpp b/src/server2/dpl/core/src/exception.cpp
deleted file mode 100644 (file)
index d1635bc..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2011 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        exception.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation of exception system
- */
-#include <stddef.h>
-#include <dpl/exception.h>
-#include <dpl/log/log.h>
-#include <cstdio>
-
-namespace SecurityServer {
-Exception* Exception::m_lastException = NULL;
-unsigned int Exception::m_exceptionCount = 0;
-void (*Exception::m_terminateHandler)() = NULL;
-
-void LogUnhandledException(const std::string &str)
-{
-    // Logging to console
-    printf("%s\n", str.c_str());
-
-    // Logging to dlog
-    LogPedantic(str);
-}
-
-void LogUnhandledException(const std::string &str,
-                           const char *filename,
-                           int line,
-                           const char *function)
-{
-    // Logging to console
-    std::ostringstream msg;
-    msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " <<
-    function << " ===\033[m";
-    msg << str;
-    printf("%s\n", msg.str().c_str());
-
-    // Logging to dlog
-    SecurityServer::Log::LogSystemSingleton::Instance().Error(
-        str.c_str(), filename, line, function);
-}
-} // namespace SecurityServer
diff --git a/src/server2/dpl/core/src/noncopyable.cpp b/src/server2/dpl/core/src/noncopyable.cpp
deleted file mode 100644 (file)
index c58e25a..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2011 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        noncopyable.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of noncopyable
- */
-#include <stddef.h>
-#include <dpl/noncopyable.h>
-
-namespace SecurityServer {
-Noncopyable::Noncopyable()
-{}
-
-Noncopyable::~Noncopyable()
-{}
-} // namespace SecurityServer
diff --git a/src/server2/dpl/core/src/serialization.cpp b/src/server2/dpl/core/src/serialization.cpp
deleted file mode 100644 (file)
index f8f05ff..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2011 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.cpp
- * @author      Tomasz Swierczek (t.swierczek@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of data serialization.
- */
-#include <stddef.h>
-#include <dpl/serialization.h>
-
-//
-// Note:
-//
-// The file here is left blank to enable precompilation
-// of templates in corresponding header file.
-// Do not remove this file.
-//
diff --git a/src/server2/dpl/core/src/singleton.cpp b/src/server2/dpl/core/src/singleton.cpp
deleted file mode 100644 (file)
index a76e8ac..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2011 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        generic_event.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of singleton
- */
-#include <stddef.h>
-#include <dpl/singleton.h>
-
-//
-// Note:
-//
-// The file here is left blank to enable precompilation
-// of templates in corresponding header file.
-// Do not remove this file.
-//
diff --git a/src/server2/dpl/log/include/dpl/log/abstract_log_provider.h b/src/server2/dpl/log/include/dpl/log/abstract_log_provider.h
deleted file mode 100644 (file)
index 7679924..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (c) 2011 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        abstract_log_provider.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of abstract log provider
- */
-#ifndef SECURITYSERVER_ABSTRACT_LOG_PROVIDER_H
-#define SECURITYSERVER_ABSTRACT_LOG_PROVIDER_H
-
-namespace SecurityServer {
-namespace Log {
-class AbstractLogProvider
-{
-  public:
-    virtual ~AbstractLogProvider() {}
-
-    virtual void SetTag(const char *tag);
-
-    virtual void Debug(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function) = 0;
-    virtual void Info(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function) = 0;
-    virtual void Warning(const char *message,
-                         const char *fileName,
-                         int line,
-                         const char *function) = 0;
-    virtual void Error(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function) = 0;
-    virtual void Pedantic(const char *message,
-                          const char *fileName,
-                          int line,
-                          const char *function) = 0;
-    virtual void SecureDebug(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function) = 0;
-    virtual void SecureInfo(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function) = 0;
-    virtual void SecureWarning(const char *message,
-                         const char *fileName,
-                         int line,
-                         const char *function) = 0;
-    virtual void SecureError(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function) = 0;
-    virtual void SmackAudit(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function) = 0;
-
-  protected:
-    static const char *LocateSourceFileName(const char *filename);
-};
-}
-} // namespace SecurityServer
-
-#endif // SECURITYSERVER_ABSTRACT_LOG_PROVIDER_H
diff --git a/src/server2/dpl/log/include/dpl/log/audit-smack-log.h b/src/server2/dpl/log/include/dpl/log/audit-smack-log.h
deleted file mode 100644 (file)
index 912ad53..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        audit-smack-log.h
- * @author      Marek Smolinski (m.smolinski@samsung.com)
- * @version     1.0
- * @brief       AuditSmackLog loging SMACK access deny sequentially into files
- */
-
-#ifndef _AUDIT_SMACK_LOG_
-#define _AUDIT_SMACK_LOG_
-
-#include <dpl/log/abstract_log_provider.h>
-
-#include <map>
-#include <fstream>
-#include <mutex>
-#include <memory>
-#include <functional>
-
-namespace SecurityServer {
-namespace Log {
-
-class AuditSmackLog :
-    public AbstractLogProvider
-{
-public:
-    AuditSmackLog();
-    virtual ~AuditSmackLog();
-
-    bool Fail() const;
-
-    virtual void Debug(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void Info(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function);
-    virtual void Warning(const char *message,
-                         const char *fileName,
-                         int line,
-                         const char *function);
-    virtual void Error(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void Pedantic(const char *message,
-                          const char *fileName,
-                          int line,
-                          const char *function);
-    virtual void SecureDebug(const char *message,
-                             const char *fileName,
-                             int line,
-                             const char *function);
-    virtual void SecureInfo(const char *message,
-                            const char *fileName,
-                            int line,
-                            const char *function);
-    virtual void SecureWarning(const char *message,
-                              const char *fileName,
-                              int line,
-                              const char *function);
-    virtual void SecureError(const char *message,
-                             const char *fileName,
-                             int line,
-                             const char *function);
-
-    virtual void SmackAudit(const char *message,
-                            const char *fileName,
-                            int line,
-                            const char *function);
-
-private:
-    void HandleWrite(const char *message,
-                     const char *fileName,
-                     int line,
-                     const char *function);
-
-    int CreateLogFile();
-    int RemoveOldestLogFile();
-    int ParseConfig();
-    int ProcessLogDir();
-    bool IsFileFull(std::ofstream &fs) const;
-
-    bool m_state;
-    unsigned int m_filesCount;
-    unsigned int m_fileMaxBytesSize;
-
-    std::map<time_t, std::string> m_fileNameMap;
-    std::ofstream m_outputStream;
-
-    std::mutex m_writeMtx;
-};
-
-}  // namespace Log
-}  // namespace SecurityServer
-#endif  // _AUDIT_SMACK_LOG_
diff --git a/src/server2/dpl/log/include/dpl/log/dlog_log_provider.h b/src/server2/dpl/log/include/dpl/log/dlog_log_provider.h
deleted file mode 100644 (file)
index cd76c46..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2011 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_log_provider.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of DLOG log provider
- */
-#ifndef SECURITYSERVER_DLOG_LOG_PROVIDER_H
-#define SECURITYSERVER_DLOG_LOG_PROVIDER_H
-
-#include <dpl/log/abstract_log_provider.h>
-#include <memory>
-#include <string>
-
-namespace SecurityServer {
-namespace Log {
-class DLOGLogProvider :
-    public AbstractLogProvider
-{
-  private:
-    std::unique_ptr<char[]> m_tag;
-
-    static std::string FormatMessage(const char *message,
-                                     const char *filename,
-                                     int line,
-                                     const char *function);
-
-  public:
-    DLOGLogProvider();
-    virtual ~DLOGLogProvider();
-
-    virtual void Debug(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void Info(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function);
-    virtual void Warning(const char *message,
-                         const char *fileName,
-                         int line,
-                         const char *function);
-    virtual void Error(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void Pedantic(const char *message,
-                          const char *fileName,
-                          int line,
-                          const char *function);
-    virtual void SecureDebug(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void SecureInfo(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function);
-    virtual void SecureWarning(const char *message,
-                         const char *fileName,
-                         int line,
-                         const char *function);
-    virtual void SecureError(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void SmackAudit(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-
-    // Set global Tag according to DLOG
-    void SetTag(const char *tag);
-};
-
-} // namespace Log
-} // namespace SecurityServer
-
-#endif // SECURITYSERVER_DLOG_LOG_PROVIDER_H
diff --git a/src/server2/dpl/log/include/dpl/log/log.h b/src/server2/dpl/log/include/dpl/log/log.h
deleted file mode 100644 (file)
index 9d8403a..0000000
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Copyright (c) 2011 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.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of log system
- */
-#ifndef SECURITYSERVER_LOG_H
-#define SECURITYSERVER_LOG_H
-
-#include <dpl/singleton.h>
-#include <dpl/noncopyable.h>
-#include <dpl/log/abstract_log_provider.h>
-#include <sstream>
-#include <list>
-
-namespace SecurityServer {
-namespace Log {
-/**
- * SecurityServer log system
- *
- * To switch logs into old style, export
- * DPL_USE_OLD_STYLE_LOGS before application start
- */
-class LogSystem :
-    private Noncopyable
-{
-  private:
-    typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
-    AbstractLogProviderPtrList m_providers;
-
-    bool m_isLoggingEnabled;
-
-  public:
-    bool IsLoggingEnabled() const;
-    LogSystem();
-    virtual ~LogSystem();
-
-    /**
-     * Log debug message
-     */
-    void Debug(const char *message,
-               const char *filename,
-               int line,
-               const char *function);
-
-    /**
-     * Log info message
-     */
-    void Info(const char *message,
-              const char *filename,
-              int line,
-              const char *function);
-
-    /**
-     * Log warning message
-     */
-    void Warning(const char *message,
-                 const char *filename,
-                 int line,
-                 const char *function);
-
-    /**
-     * Log error message
-     */
-    void Error(const char *message,
-               const char *filename,
-               int line,
-               const char *function);
-
-    /**
-     * Log pedantic message
-     */
-    void Pedantic(const char *message,
-                  const char *filename,
-                  int line,
-                  const char *function);
-
-    /**
-     * Log pedantic message with secure macro
-     */
-    void SecureDebug(const char *message,
-               const char *filename,
-               int line,
-               const char *function);
-
-    /**
-     * Log info message with secure macro
-     */
-    void SecureInfo(const char *message,
-              const char *filename,
-              int line,
-              const char *function);
-
-    /**
-     * Log warning message with secure macro
-     */
-    void SecureWarning(const char *message,
-                 const char *filename,
-                 int line,
-                 const char *function);
-
-    /**
-     * Log error message with secure macro
-     */
-    void SecureError(const char *message,
-               const char *filename,
-               int line,
-               const char *function);
-
-    /**
-     * Log SS_SMACK into files
-     */
-     void SmackAudit(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function);
-
-    /**
-     * Set default's DLOG provider Tag
-     */
-    void SetTag(const char *tag);
-
-    /**
-     * Add abstract provider to providers list
-     *
-     * @notice Ownership is transfered to LogSystem and deleted upon exit
-     */
-    void AddProvider(AbstractLogProvider *provider);
-
-    /**
-     * Remove abstract provider from providers list
-     */
-    void RemoveProvider(AbstractLogProvider *provider);
-};
-
-/*
- * Replacement low overhead null logging class
- */
-class NullStream
-{
-  public:
-    NullStream() {}
-
-    template <typename T>
-    NullStream& operator<<(const T&)
-    {
-        return *this;
-    }
-};
-
-/**
- * Log system singleton
- */
-typedef Singleton<LogSystem> LogSystemSingleton;
-}
-} // namespace SecurityServer
-
-//
-// Log support
-//
-//
-
-/* avoid warnings about unused variables */
-#define DPL_MACRO_DUMMY_LOGGING(message, function)                         \
-    do {                                                                   \
-        SecurityServer::Log::NullStream ns;                                \
-        ns << message;                                                     \
-    } while (0)
-
-#define DPL_MACRO_FOR_LOGGING(message, function)                           \
-do                                                                         \
-{                                                                          \
-    if (SecurityServer::Log::LogSystemSingleton::Instance().IsLoggingEnabled())   \
-    {                                                                      \
-        std::ostringstream platformLog;                                    \
-        platformLog << message;                                            \
-        SecurityServer::Log::LogSystemSingleton::Instance().function(      \
-            platformLog.str().c_str(),                                     \
-            __FILE__, __LINE__, __FUNCTION__);                             \
-    }                                                                      \
-} while (0)
-
-/* Errors must be always logged. */
-#define  LogError(message) DPL_MACRO_FOR_LOGGING(message, Error)
-#define  LogSecureError(message) DPL_MACRO_FOR_LOGGING(message, SecureError)
-
-#define  LogSmackAudit(message) DPL_MACRO_FOR_LOGGING(message, SmackAudit)
-
-#ifdef BUILD_TYPE_DEBUG
-    #define LogDebug(message) DPL_MACRO_FOR_LOGGING(message, Debug)
-    #define LogInfo(message) DPL_MACRO_FOR_LOGGING(message, Info)
-    #define LogWarning(message) DPL_MACRO_FOR_LOGGING(message, Warning)
-    #define LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, Pedantic)
-    #define LogSecureDebug(message) DPL_MACRO_FOR_LOGGING(message, SecureDebug)
-    #define LogSecureInfo(message) DPL_MACRO_FOR_LOGGING(message, SecureInfo)
-    #define LogSecureWarning(message) DPL_MACRO_FOR_LOGGING(message, SecureWarning)
-#else
-    #define LogDebug(message) DPL_MACRO_DUMMY_LOGGING(message, Debug)
-    #define LogInfo(message) DPL_MACRO_DUMMY_LOGGING(message, Info)
-    #define LogWarning(message) DPL_MACRO_DUMMY_LOGGING(message, Warning)
-    #define LogPedantic(message) DPL_MACRO_DUMMY_LOGGING(message, Pedantic)
-    #define LogSecureDebug(message) DPL_MACRO_DUMMY_LOGGING(message, SecureDebug)
-    #define LogSecureInfo(message) DPL_MACRO_DUMMY_LOGGING(message, SecureInfo)
-    #define LogSecureWarning(message) DPL_MACRO_DUMMY_LOGGING(message, SecureWarning)
-#endif // BUILD_TYPE_DEBUG
-
-#endif // SECURITYSERVER_LOG_H
diff --git a/src/server2/dpl/log/include/dpl/log/old_style_log_provider.h b/src/server2/dpl/log/include/dpl/log/old_style_log_provider.h
deleted file mode 100644 (file)
index 91eeb80..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2011 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        old_style_log_provider.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of old style log provider
- */
-#ifndef SECURITYSERVER_OLD_STYLE_LOG_PROVIDER_H
-#define SECURITYSERVER_OLD_STYLE_LOG_PROVIDER_H
-
-#include <dpl/log/abstract_log_provider.h>
-#include <string>
-
-namespace SecurityServer {
-namespace Log {
-class OldStyleLogProvider :
-    public AbstractLogProvider
-{
-  private:
-    bool m_showDebug;
-    bool m_showInfo;
-    bool m_showWarning;
-    bool m_showError;
-    bool m_showPedantic;
-    bool m_printStdErr;
-
-    static std::string FormatMessage(const char *message,
-                                     const char *filename,
-                                     int line,
-                                     const char *function);
-
-  public:
-    OldStyleLogProvider(bool showDebug,
-                        bool showInfo,
-                        bool showWarning,
-                        bool showError,
-                        bool showPedantic);
-    OldStyleLogProvider(bool showDebug,
-                        bool showInfo,
-                        bool showWarning,
-                        bool showError,
-                        bool showPedantic,
-                        bool printStdErr);
-    virtual ~OldStyleLogProvider() {}
-
-    virtual void Debug(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void Info(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function);
-    virtual void Warning(const char *message,
-                         const char *fileName,
-                         int line,
-                         const char *function);
-    virtual void Error(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void Pedantic(const char *message,
-                          const char *fileName,
-                          int line,
-                          const char *function);
-    virtual void SecureDebug(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void SecureInfo(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function);
-    virtual void SecureWarning(const char *message,
-                         const char *fileName,
-                         int line,
-                         const char *function);
-    virtual void SecureError(const char *message,
-                       const char *fileName,
-                       int line,
-                       const char *function);
-    virtual void SmackAudit(const char *message,
-                      const char *fileName,
-                      int line,
-                      const char *function);
-};
-}
-} // namespace SecurityServer
-
-#endif // SECURITYSERVER_OLD_STYLE_LOG_PROVIDER_H
diff --git a/src/server2/dpl/log/src/abstract_log_provider.cpp b/src/server2/dpl/log/src/abstract_log_provider.cpp
deleted file mode 100644 (file)
index 1da7bba..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2011 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        abstract_log_provider.cpp
- * @author      Pawel Sikorski (p.sikorski@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of abstract log provider
- */
-#include <stddef.h>
-#include <dpl/log/abstract_log_provider.h>
-#include <cstring>
-
-#define UNUSED __attribute__((unused))
-
-namespace SecurityServer {
-namespace Log {
-
-void AbstractLogProvider::SetTag(const char *tag UNUSED) {}
-
-const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
-{
-    const char *ptr = strrchr(filename, '/');
-    return ptr != NULL ? ptr + 1 : filename;
-}
-}
-}
diff --git a/src/server2/dpl/log/src/audit-smack-log.cpp b/src/server2/dpl/log/src/audit-smack-log.cpp
deleted file mode 100644 (file)
index c442955..0000000
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        audit-smack-log.cpp
- * @author      Marek Smolinski (m.smolinski@samsung.com)
- * @version     1.0
- * @brief       AuditSmackLog loging SMACK access deny sequentially into files
- */
-
-#include <iostream>
-#include <fstream>
-#include <map>
-#include <cstring>
-#include <mutex>
-
-#include <dirent.h>
-#include <time.h>
-#include <errno.h>
-#include <unistd.h>
-#include <cassert>
-
-#include <sys/smack.h>
-#include <sys/stat.h>
-
-#include <dpl/log/audit-smack-log.h>
-#include <dpl/log/log.h>
-
-#define UNUSED __attribute__((unused))
-
-namespace {
-
-const std::string AUDIT_CONFIG_LOG_PATH = "/etc/security/";
-const std::string AUDIT_CONFIG_FILENAME = "security-server-audit.conf";
-const std::string AUDIT_LOG_DIRECTORY = "/var/log/audit/";
-const std::string AUDIT_LOG_FILENAME_PREFIX = "audit-smack";
-const std::string AUDIT_LOG_SMACK_LABEL = "security-server::audit-files";
-
-} // namespace anonymous
-
-namespace SecurityServer {
-namespace Log {
-
-AuditSmackLog::AuditSmackLog()
-    : m_state(true), m_filesCount(0), m_fileMaxBytesSize(0)
-{
-    if (ParseConfig() != 0) {
-        goto error;
-    }
-
-    if (ProcessLogDir() != 0) {
-        goto error;
-    }
-
-    if (m_state) {
-
-        // reduce existing files count in log dir if config file was changed
-        while (m_fileNameMap.size() > m_filesCount) {
-            if (RemoveOldestLogFile() != 0) {
-                goto error;
-            }
-        }
-
-        if (m_fileNameMap.size() == 0) {
-            if (CreateLogFile() != 0) {
-                goto error;
-            }
-        } else {
-            std::string filename(AUDIT_LOG_DIRECTORY);
-            filename += m_fileNameMap.rbegin()->second;
-            m_outputStream.open(filename, std::ios_base::app);
-        }
-    }
-
-    return;
-
-error:
-    m_state = false;
-
-}
-
-AuditSmackLog::~AuditSmackLog(){}
-
-bool AuditSmackLog::Fail() const
-{
-    return !m_state;
-}
-
-void AuditSmackLog::SmackAudit(const char *message,
-                               const char *fileName,
-                               int line,
-                               const char *function)
-{
-    if (m_state) {
-        HandleWrite(message, fileName, line, function);
-    }
-}
-
-void AuditSmackLog::HandleWrite(const char *message,
-                                const char *filename,
-                                int line,
-                                const char *function)
-{
-    std::lock_guard<std::mutex> lock(m_writeMtx);
-    if (IsFileFull(m_outputStream)) {
-        if (CreateLogFile() != 0) {
-            m_state = false;
-            return;
-        }
-
-        if (m_fileNameMap.size() > m_filesCount) {
-            if (RemoveOldestLogFile() != 0) {
-                m_state = false;
-                return;
-            }
-        }
-    }
-
-    m_outputStream << std::string("[") <<
-        LocateSourceFileName(filename) << std::string(":") << line <<
-        std::string("] ") << function << std::string("(): ") << message << '\n';
-}
-
-int AuditSmackLog::CreateLogFile()
-{
-    time_t sec = time(NULL);
-    std::string fname(AUDIT_LOG_FILENAME_PREFIX);
-    std::string pathname(AUDIT_LOG_DIRECTORY);
-
-    fname += std::to_string(sec);
-    fname += ".log";
-    pathname += fname;
-
-    if (m_outputStream.is_open())
-        m_outputStream.close();
-
-    m_outputStream.open(pathname.c_str());
-
-    if (!m_outputStream) {
-        return -1;
-    }
-
-    if (smack_setlabel(pathname.c_str(),
-                       AUDIT_LOG_SMACK_LABEL.c_str(),
-                       SMACK_LABEL_ACCESS) != 0)  {
-        return -1;
-    }
-
-    m_fileNameMap.insert(std::make_pair(sec, fname));
-    return 0;
-}
-
-int AuditSmackLog::RemoveOldestLogFile()
-{
-    assert(m_fileNameMap.size() > 0);
-
-    auto it = m_fileNameMap.begin();
-    std::string filename(AUDIT_LOG_DIRECTORY);
-    filename += it->second;
-
-    if (unlink(filename.c_str()) == 0) {
-        m_fileNameMap.erase(it);
-        return 0;
-    }
-
-    return -1;
-}
-
-int AuditSmackLog::ParseConfig()
-{
-    struct stat sb;
-    if (stat(AUDIT_CONFIG_LOG_PATH.c_str(), &sb) != 0) {
-        return -1;
-    }
-
-    std::ifstream in(AUDIT_CONFIG_LOG_PATH + AUDIT_CONFIG_FILENAME,
-                     std::ios_base::in);
-    if (!in) {
-        return -1;
-    }
-
-    in >> m_filesCount >> m_fileMaxBytesSize;
-
-    if (in.fail()) {
-        return -1;
-    }
-
-    return (m_filesCount > 0 && m_fileMaxBytesSize > 0) ? 0 : -1;
-}
-
-int AuditSmackLog::ProcessLogDir()
-{
-    DIR *dir;
-    dirent *dp;
-
-    if ((dir = opendir(AUDIT_LOG_DIRECTORY.c_str())) == NULL) {
-        return -1;
-    }
-
-    while ((dp = readdir(dir)) != NULL) {
-        if (AUDIT_LOG_FILENAME_PREFIX.compare(0, std::string::npos,
-                                      dp->d_name,
-                                      AUDIT_LOG_FILENAME_PREFIX.size()) == 0) {
-            errno = 0;
-            char *pEnd;
-            time_t fUnxTime = static_cast<time_t>(
-                    strtoull(dp->d_name + AUDIT_LOG_FILENAME_PREFIX.size(),
-                             &pEnd, 10));
-
-            if (errno != 0) {
-                closedir(dir);
-                return -1;
-            }
-
-            m_fileNameMap.insert(
-                    std::make_pair(fUnxTime, std::string(dp->d_name)));
-        }
-    }
-
-    closedir(dir);
-
-    return 0;
-}
-
-bool AuditSmackLog::IsFileFull(std::ofstream &fs) const
-{
-    return fs.tellp() > m_fileMaxBytesSize;
-}
-
-void AuditSmackLog::Debug(const char *message UNUSED,
-                          const char *filename UNUSED,
-                          int line UNUSED,
-                          const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::Info(const char *message UNUSED,
-                         const char *filename UNUSED,
-                         int line UNUSED,
-                         const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::Warning(const char *message UNUSED,
-                            const char *filename UNUSED,
-                            int line UNUSED,
-                            const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::Error(const char *message UNUSED,
-                          const char *filename UNUSED,
-                          int line UNUSED,
-                          const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::Pedantic(const char *message UNUSED,
-                             const char *filename UNUSED,
-                             int line UNUSED,
-                             const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::SecureDebug(const char *message UNUSED,
-                                const char *filename UNUSED,
-                                int line UNUSED,
-                                const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::SecureInfo(const char *message UNUSED,
-                               const char *filename  UNUSED,
-                               int line  UNUSED,
-                               const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::SecureWarning(const char *message UNUSED,
-                                  const char *filename UNUSED,
-                                  int line UNUSED,
-                                  const char *function UNUSED)
-{
-}
-
-void AuditSmackLog::SecureError(const char *message UNUSED,
-                                const char *filename UNUSED,
-                                int line UNUSED,
-                                const char *function UNUSED)
-{
-}
-
-} // namespace Log
-} // namespace SecurityServer
diff --git a/src/server2/dpl/log/src/dlog_log_provider.cpp b/src/server2/dpl/log/src/dlog_log_provider.cpp
deleted file mode 100644 (file)
index 90f0713..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (c) 2011 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_log_provider.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of DLOG log provider
- */
-#include <stddef.h>
-#include <dpl/log/dlog_log_provider.h>
-#include <cstring>
-#include <sstream>
-#include <dlog.h>
-
-#define UNUSED __attribute__((unused))
-
-namespace SecurityServer {
-namespace Log {
-std::string DLOGLogProvider::FormatMessage(const char *message,
-                                           const char *filename,
-                                           int line,
-                                           const char *function)
-{
-    std::ostringstream val;
-
-    val << std::string("[") <<
-    LocateSourceFileName(filename) << std::string(":") << line <<
-    std::string("] ") << function << std::string("(): ") << message;
-
-    return val.str();
-}
-
-DLOGLogProvider::DLOGLogProvider()
-{}
-
-DLOGLogProvider::~DLOGLogProvider()
-{}
-
-void DLOGLogProvider::SetTag(const char *tag)
-{
-    size_t size = strlen(tag)+1;
-    char *buff = new (std::nothrow) char[size];
-    if (buff)
-        memcpy(buff, tag, size);
-    m_tag.reset(buff);
-}
-
-void DLOGLogProvider::Debug(const char *message,
-                            const char *filename,
-                            int line,
-                            const char *function)
-{
-    SLOG(LOG_DEBUG, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::Info(const char *message,
-                           const char *filename,
-                           int line,
-                           const char *function)
-{
-    SLOG(LOG_INFO, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::Warning(const char *message,
-                              const char *filename,
-                              int line,
-                              const char *function)
-{
-    SLOG(LOG_WARN, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::Error(const char *message,
-                            const char *filename,
-                            int line,
-                            const char *function)
-{
-    SLOG(LOG_ERROR, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::Pedantic(const char *message,
-                               const char *filename,
-                               int line,
-                               const char *function)
-{
-    SLOG(LOG_DEBUG, "SecurityServer", "%s", FormatMessage(message,
-                                              filename,
-                                              line,
-                                              function).c_str());
-}
-
-void DLOGLogProvider::SecureDebug(const char *message UNUSED,
-                            const char *filename UNUSED,
-                            int line UNUSED,
-                            const char *function UNUSED)
-{
-    SECURE_SLOG(LOG_DEBUG, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::SecureInfo(const char *message UNUSED,
-                           const char *filename UNUSED,
-                           int line UNUSED,
-                           const char *function UNUSED)
-{
-    SECURE_SLOG(LOG_INFO, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::SecureWarning(const char *message UNUSED,
-                              const char *filename UNUSED,
-                              int line UNUSED,
-                              const char *function UNUSED)
-{
-    SECURE_SLOG(LOG_WARN, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::SecureError(const char *message UNUSED,
-                            const char *filename UNUSED,
-                            int line UNUSED,
-                            const char *function UNUSED)
-{
-    SECURE_SLOG(LOG_ERROR, m_tag.get(), "%s",
-        FormatMessage(message, filename, line, function).c_str());
-}
-
-void DLOGLogProvider::SmackAudit(const char *message UNUSED,
-                           const char *filename UNUSED,
-                           int line UNUSED,
-                           const char *function UNUSED)
-{
-}
-
-} // nemespace Log
-} // namespace SecurityServer
diff --git a/src/server2/dpl/log/src/log.cpp b/src/server2/dpl/log/src/log.cpp
deleted file mode 100644 (file)
index a91cdb2..0000000
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Copyright (c) 2011 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.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of log system
- */
-#include <stddef.h>
-#include <string.h>
-
-#include <dpl/log/log.h>
-#include <dpl/singleton_impl.h>
-#include <dpl/log/dlog_log_provider.h>
-#include <dpl/log/old_style_log_provider.h>
-#include <dpl/log/audit-smack-log.h>
-
-IMPLEMENT_SINGLETON(SecurityServer::Log::LogSystem)
-
-namespace SecurityServer {
-namespace Log {
-namespace // anonymous
-{
-#ifdef BUILD_TYPE_DEBUG
-const char *OLD_STYLE_LOGS_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS";
-const char *OLD_STYLE_PEDANTIC_LOGS_ENV_NAME =
-    "DPL_USE_OLD_STYLE_PEDANTIC_LOGS";
-const char *OLD_STYLE_LOGS_MASK_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS_MASK";
-#endif // BUILD_TYPE_DEBUG
-const char *SECURITY_SERVER_LOG_OFF = "DPL_LOG_OFF";
-} // namespace anonymous
-
-bool LogSystem::IsLoggingEnabled() const
-{
-    return m_isLoggingEnabled;
-}
-
-LogSystem::LogSystem() :
-    m_isLoggingEnabled(!getenv(SECURITY_SERVER_LOG_OFF))
-{
-#ifdef BUILD_TYPE_DEBUG
-    bool oldStyleLogs = false;
-    bool oldStyleDebugLogs = true;
-    bool oldStyleInfoLogs = true;
-    bool oldStyleWarningLogs = true;
-    bool oldStyleErrorLogs = true;
-    bool oldStylePedanticLogs = false;
-
-    // Check environment settings about pedantic logs
-    const char *value = getenv(OLD_STYLE_LOGS_ENV_NAME);
-
-    if (value != NULL && !strcmp(value, "1")) {
-        oldStyleLogs = true;
-    }
-
-    value = getenv(OLD_STYLE_PEDANTIC_LOGS_ENV_NAME);
-
-    if (value != NULL && !strcmp(value, "1")) {
-        oldStylePedanticLogs = true;
-    }
-
-    value = getenv(OLD_STYLE_LOGS_MASK_ENV_NAME);
-
-    if (value != NULL) {
-        size_t len = strlen(value);
-
-        if (len >= 1) {
-            if (value[0] == '0') {
-                oldStyleDebugLogs = false;
-            } else if (value[0] == '1') {
-                oldStyleDebugLogs = true;
-            }
-        }
-
-        if (len >= 2) {
-            if (value[1] == '0') {
-                oldStyleInfoLogs = false;
-            } else if (value[1] == '1') {
-                oldStyleInfoLogs = true;
-            }
-        }
-
-        if (len >= 3) {
-            if (value[2] == '0') {
-                oldStyleWarningLogs = false;
-            } else if (value[2] == '1') {
-                oldStyleWarningLogs = true;
-            }
-        }
-
-        if (len >= 4) {
-            if (value[3] == '0') {
-                oldStyleErrorLogs = false;
-            } else if (value[3] == '1') {
-                oldStyleErrorLogs = true;
-            }
-        }
-    }
-
-    // Setup default DLOG and old style logging
-    if (oldStyleLogs) {
-        // Old style
-        AddProvider(new OldStyleLogProvider(oldStyleDebugLogs,
-                                            oldStyleInfoLogs,
-                                            oldStyleWarningLogs,
-                                            oldStyleErrorLogs,
-                                            oldStylePedanticLogs));
-    } else {
-        // DLOG
-        AddProvider(new DLOGLogProvider());
-    }
-#else // BUILD_TYPE_DEBUG
-    AddProvider(new DLOGLogProvider());
-#endif // BUILD_TYPE_DEBUG
-
-    AuditSmackLog * smackLog = new AuditSmackLog();
-    if (smackLog->Fail()) {
-        delete smackLog;
-    } else {
-        AddProvider(smackLog);
-    }
-}
-
-LogSystem::~LogSystem()
-{
-    // Delete all providers
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        delete *iterator;
-    }
-
-    m_providers.clear();
-}
-
-void LogSystem::SetTag(const char* tag)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->SetTag(tag);
-    }
-}
-
-void LogSystem::AddProvider(AbstractLogProvider *provider)
-{
-    m_providers.push_back(provider);
-}
-
-void LogSystem::RemoveProvider(AbstractLogProvider *provider)
-{
-    m_providers.remove(provider);
-}
-
-void LogSystem::Debug(const char *message,
-                      const char *filename,
-                      int line,
-                      const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->Debug(message, filename, line, function);
-    }
-}
-
-void LogSystem::Info(const char *message,
-                     const char *filename,
-                     int line,
-                     const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->Info(message, filename, line, function);
-    }
-}
-
-void LogSystem::Warning(const char *message,
-                        const char *filename,
-                        int line,
-                        const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->Warning(message, filename, line, function);
-    }
-}
-
-void LogSystem::Error(const char *message,
-                      const char *filename,
-                      int line,
-                      const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->Error(message, filename, line, function);
-    }
-}
-
-void LogSystem::Pedantic(const char *message,
-                         const char *filename,
-                         int line,
-                         const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->Pedantic(message, filename, line, function);
-    }
-}
-
-void LogSystem::SecureInfo(const char *message,
-                         const char *filename,
-                         int line,
-                         const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->SecureInfo(message, filename, line, function);
-    }
-}
-
-void LogSystem::SecureDebug(const char *message,
-                         const char *filename,
-                         int line,
-                         const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->SecureDebug(message, filename, line, function);
-    }
-}
-
-void LogSystem::SecureError(const char *message,
-                         const char *filename,
-                         int line,
-                         const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->SecureError(message, filename, line, function);
-    }
-}
-
-void LogSystem::SecureWarning(const char *message,
-                         const char *filename,
-                         int line,
-                         const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->SecureWarning(message, filename, line, function);
-    }
-}
-
-void LogSystem::SmackAudit(const char *message,
-                     const char *fileName,
-                     int line,
-                     const char *function)
-{
-    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
-         iterator != m_providers.end();
-         ++iterator)
-    {
-        (*iterator)->SmackAudit(message, fileName, line, function);
-    }
-}
-
-}
-} // namespace SecurityServer
diff --git a/src/server2/dpl/log/src/old_style_log_provider.cpp b/src/server2/dpl/log/src/old_style_log_provider.cpp
deleted file mode 100644 (file)
index 4c10749..0000000
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Copyright (c) 2011 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        old_style_log_provider.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of old style log provider
- */
-#include <stddef.h>
-#include <dpl/log/old_style_log_provider.h>
-#include <dpl/colors.h>
-#include <cstdio>
-#include <cstring>
-#include <sstream>
-#include <sys/time.h>
-#include <unistd.h>
-#include <dlog.h>
-
-namespace SecurityServer {
-namespace Log {
-namespace // anonymous
-{
-using namespace SecurityServer::Colors::Text;
-const char *DEBUG_BEGIN = GREEN_BEGIN;
-const char *DEBUG_END = GREEN_END;
-const char *INFO_BEGIN = CYAN_BEGIN;
-const char *INFO_END = CYAN_END;
-const char *ERROR_BEGIN = RED_BEGIN;
-const char *ERROR_END = RED_END;
-const char *WARNING_BEGIN = BOLD_GOLD_BEGIN;
-const char *WARNING_END = BOLD_GOLD_END;
-const char *PEDANTIC_BEGIN = PURPLE_BEGIN;
-const char *PEDANTIC_END = PURPLE_END;
-
-std::string GetFormattedTime()
-{
-    timeval tv;
-    tm localNowTime;
-
-    gettimeofday(&tv, NULL);
-    localtime_r(&tv.tv_sec, &localNowTime);
-
-    char format[64];
-    snprintf(format,
-             sizeof(format),
-             "%02i:%02i:%02i.%03i",
-             localNowTime.tm_hour,
-             localNowTime.tm_min,
-             localNowTime.tm_sec,
-             static_cast<int>(tv.tv_usec / 1000));
-    return format;
-}
-} // namespace anonymous
-
-std::string OldStyleLogProvider::FormatMessage(const char *message,
-                                               const char *filename,
-                                               int line,
-                                               const char *function)
-{
-    std::ostringstream val;
-
-    val << std::string("[") << GetFormattedTime() << std::string("] [") <<
-    static_cast<unsigned long>(pthread_self()) << "/" <<
-    static_cast<int>(getpid()) << std::string("] [") <<
-    LocateSourceFileName(filename) << std::string(":") << line <<
-    std::string("] ") << function << std::string("(): ") << message;
-
-    return val.str();
-}
-
-OldStyleLogProvider::OldStyleLogProvider(bool showDebug,
-                                         bool showInfo,
-                                         bool showWarning,
-                                         bool showError,
-                                         bool showPedantic) :
-    m_showDebug(showDebug),
-    m_showInfo(showInfo),
-    m_showWarning(showWarning),
-    m_showError(showError),
-    m_showPedantic(showPedantic),
-    m_printStdErr(false)
-{}
-
-OldStyleLogProvider::OldStyleLogProvider(bool showDebug,
-                                         bool showInfo,
-                                         bool showWarning,
-                                         bool showError,
-                                         bool showPedantic,
-                                         bool printStdErr) :
-    m_showDebug(showDebug),
-    m_showInfo(showInfo),
-    m_showWarning(showWarning),
-    m_showError(showError),
-    m_showPedantic(showPedantic),
-    m_printStdErr(printStdErr)
-{}
-
-void OldStyleLogProvider::Debug(const char *message,
-                                const char *filename,
-                                int line,
-                                const char *function)
-{
-    if (m_showDebug) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), DEBUG_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), DEBUG_END);
-        }
-    }
-}
-
-void OldStyleLogProvider::Info(const char *message,
-                               const char *filename,
-                               int line,
-                               const char *function)
-{
-    if (m_showInfo) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), INFO_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), INFO_END);
-        }
-    }
-}
-
-void OldStyleLogProvider::Warning(const char *message,
-                                  const char *filename,
-                                  int line,
-                                  const char *function)
-{
-    if (m_showWarning) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), WARNING_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), WARNING_END);
-        }
-    }
-}
-
-void OldStyleLogProvider::Error(const char *message,
-                                const char *filename,
-                                int line,
-                                const char *function)
-{
-    if (m_showError) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), ERROR_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), ERROR_END);
-        }
-    }
-}
-
-void OldStyleLogProvider::Pedantic(const char *message,
-                                   const char *filename,
-                                   int line,
-                                   const char *function)
-{
-    if (m_showPedantic) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", PEDANTIC_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), PEDANTIC_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", PEDANTIC_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), PEDANTIC_END);
-        }
-    }
-}
-
-void OldStyleLogProvider::SecureDebug(const char *message,
-                                const char *filename,
-                                int line,
-                                const char *function)
-{
-#ifdef _SECURE_LOG
-    if (m_showDebug) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), DEBUG_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), DEBUG_END);
-        }
-    }
-#else
-    (void)message;
-    (void)filename;
-    (void)line;
-    (void)function;
-#endif
-}
-
-void OldStyleLogProvider::SecureInfo(const char *message,
-                               const char *filename,
-                               int line,
-                               const char *function)
-{
-#ifdef _SECURE_LOG
-    if (m_showInfo) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), INFO_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), INFO_END);
-        }
-    }
-#else
-    (void)message;
-    (void)filename;
-    (void)line;
-    (void)function;
-#endif
-}
-
-void OldStyleLogProvider::SecureWarning(const char *message,
-                                  const char *filename,
-                                  int line,
-                                  const char *function)
-{
-#ifdef _SECURE_LOG
-    if (m_showWarning) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), WARNING_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), WARNING_END);
-        }
-    }
-#else
-    (void)message;
-    (void)filename;
-    (void)line;
-    (void)function;
-#endif
-}
-
-void OldStyleLogProvider::SecureError(const char *message,
-                                const char *filename,
-                                int line,
-                                const char *function)
-{
-#ifdef _SECURE_LOG
-    if (m_showError) {
-        if (m_printStdErr) {
-            fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), ERROR_END);
-        } else {
-            fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
-                    FormatMessage(message, filename, line,
-                        function).c_str(), ERROR_END);
-        }
-    }
-#else
-    (void)message;
-    (void)filename;
-    (void)line;
-    (void)function;
-#endif
-}
-
-void OldStyleLogProvider::SmackAudit(const char *message,
-                               const char *fileName,
-                               int line,
-                               const char *function)
-{
-    (void)message;
-    (void)fileName;
-    (void)line;
-    (void)function;
-}
-
-}
-} // namespace SecurityServer
diff --git a/src/server2/main/generic-event.h b/src/server2/main/generic-event.h
deleted file mode 100644 (file)
index 30d9e88..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        protocols.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of GenericEvent.
- */
-
-#ifndef _SECURITY_SERVER_GENERIC_EVENT_
-#define _SECURITY_SERVER_GENERIC_EVENT_
-
-namespace SecurityServer {
-
-struct GenericEvent {
-    virtual ~GenericEvent(){}
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_GENERIC_EVENT_
diff --git a/src/server2/main/generic-socket-manager.cpp b/src/server2/main/generic-socket-manager.cpp
deleted file mode 100644 (file)
index 5bf0695..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        generic-socket-manager.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of GenericSocketService and GenericSocketManager.
- */
-
-#include <sys/socket.h>
-#include <sys/types.h>
-
-#include <generic-socket-manager.h>
-
-namespace SecurityServer {
-
-class SendMsgData::Internal {
-public:
-    Internal(int resultCode, int fileDesc)
-      : m_resultCode(resultCode)
-      , m_fileDesc(fileDesc)
-    {
-        memset(&m_hdr, 0, sizeof(msghdr));
-        memset(m_cmsgbuf, 0, CMSG_SPACE(sizeof(int)));
-
-        m_iov.iov_base = &m_resultCode;
-        m_iov.iov_len = sizeof(m_resultCode);
-
-        m_hdr.msg_iov = &m_iov;
-        m_hdr.msg_iovlen = 1;
-
-        if (fileDesc != -1) {
-            m_hdr.msg_control = m_cmsgbuf;
-            m_hdr.msg_controllen = CMSG_SPACE(sizeof(int));
-
-            m_cmsg = CMSG_FIRSTHDR(&m_hdr);
-            m_cmsg->cmsg_len = CMSG_LEN(sizeof(int));
-            m_cmsg->cmsg_level = SOL_SOCKET;
-            m_cmsg->cmsg_type = SCM_RIGHTS;
-
-            memmove(CMSG_DATA(m_cmsg), &m_fileDesc, sizeof(int));
-        }
-    }
-
-    msghdr* data() { return &m_hdr; }
-
-private:
-    msghdr m_hdr;
-    iovec m_iov;
-    cmsghdr *m_cmsg;
-    unsigned char m_cmsgbuf[CMSG_SPACE(sizeof(int))];
-    int m_resultCode;
-    int m_fileDesc;
-};
-
-SendMsgData::SendMsgData()
-  : m_resultCode(0)
-  , m_fileDesc(-1)
-  , m_flags(0)
-  , m_pimpl(NULL)
-{}
-
-SendMsgData::SendMsgData(int resultCode, int fileDesc, int flags)
-  : m_resultCode(resultCode)
-  , m_fileDesc(fileDesc)
-  , m_flags(flags)
-  , m_pimpl(NULL)
-{}
-
-SendMsgData::SendMsgData(const SendMsgData &second)
-  : m_resultCode(second.m_resultCode)
-  , m_fileDesc(second.m_fileDesc)
-  , m_flags(second.m_flags)
-  , m_pimpl(NULL)
-{}
-
-SendMsgData::~SendMsgData() {
-    delete m_pimpl;
-}
-
-SendMsgData& SendMsgData::operator=(const SendMsgData &second) {
-    m_resultCode = second.m_resultCode;
-    m_fileDesc = second.m_fileDesc;
-    m_flags = second.m_flags;
-    delete m_pimpl;
-    m_pimpl = NULL;
-    return *this;
-}
-
-msghdr* SendMsgData::getMsghdr() {
-    if (!m_pimpl)
-        m_pimpl = new Internal(m_resultCode, m_fileDesc);
-    return m_pimpl->data();
-}
-
-int SendMsgData::flags() {
-    return m_flags;
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/main/generic-socket-manager.h b/src/server2/main/generic-socket-manager.h
deleted file mode 100644 (file)
index 4417a30..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        generic-socket-manager.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of GenericSocketService and GenericSocketManager.
- */
-
-#ifndef _SECURITY_SERVER_GENERIC_SERVICE_MANAGER_
-#define _SECURITY_SERVER_GENERIC_SERVICE_MANAGER_
-
-#include <vector>
-#include <string>
-
-#include <dpl/exception.h>
-
-#include <generic-event.h>
-
-extern "C" {
-struct msghdr;
-} // extern "C"
-
-namespace SecurityServer {
-
-typedef int InterfaceID;
-
-struct ConnectionID {
-    int sock;                                 // This is decriptor used for connection
-    int counter;                              // Unique handler per socket
-    inline bool operator<(const ConnectionID &second) const {
-        return counter < second.counter;
-    }
-};
-
-typedef std::vector<unsigned char> RawBuffer;
-
-struct GenericSocketManager;
-
-struct GenericSocketService {
-    typedef std::string SmackLabel;
-    typedef std::string ServiceHandlerPath;
-    struct ServiceDescription {
-        ServiceDescription(const char *path,
-            const char *smackLabel,
-            InterfaceID interfaceID = 0,
-            bool useSendMsg = false)
-          : smackLabel(smackLabel)
-          , interfaceID(interfaceID)
-          , serviceHandlerPath(path)
-          , useSendMsg(useSendMsg)
-        {}
-
-        SmackLabel smackLabel;                 // Smack label for socket
-        InterfaceID interfaceID;               // All data from serviceHandlerPath will be marked with this interfaceHandler
-        ServiceHandlerPath serviceHandlerPath; // Path to file
-        bool useSendMsg;
-    };
-
-    typedef std::vector<ServiceDescription> ServiceDescriptionVector;
-
-    struct AcceptEvent : public GenericEvent {
-        ConnectionID connectionID;
-        InterfaceID interfaceID;
-    };
-
-    struct WriteEvent : public GenericEvent {
-        ConnectionID connectionID;
-        size_t size;
-        size_t left;
-    };
-
-    struct ReadEvent : public GenericEvent {
-        ConnectionID connectionID;
-        RawBuffer rawBuffer;
-    };
-
-    struct CloseEvent : public GenericEvent {
-        ConnectionID connectionID;
-    };
-
-    virtual void SetSocketManager(GenericSocketManager *manager) {
-        m_serviceManager = manager;
-    }
-
-    virtual ServiceDescriptionVector GetServiceDescription() = 0;
-    virtual void Event(const AcceptEvent &event) = 0;
-    virtual void Event(const WriteEvent &event) = 0;
-    virtual void Event(const ReadEvent &event) = 0;
-    virtual void Event(const CloseEvent &event) = 0;
-
-    GenericSocketService() : m_serviceManager(NULL) {}
-    virtual ~GenericSocketService(){}
-protected:
-    GenericSocketManager *m_serviceManager;
-};
-
-class SendMsgData {
-public:
-    class Internal;
-
-    SendMsgData();
-    SendMsgData(int resultCode, int fileDesc, int flags = 0);
-    SendMsgData(const SendMsgData &second);
-    SendMsgData& operator=(const SendMsgData &second);
-    virtual ~SendMsgData();
-
-    msghdr* getMsghdr();
-    int flags();
-private:
-    int m_resultCode;
-    int m_fileDesc;
-    int m_flags;
-    Internal *m_pimpl;
-};
-
-struct GenericSocketManager {
-    virtual void MainLoop() = 0;
-    virtual void RegisterSocketService(GenericSocketService *ptr) = 0;
-    virtual void Close(ConnectionID connectionID) = 0;
-    virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer) = 0;
-    virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData) = 0;
-    virtual ~GenericSocketManager(){}
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_GENERIC_SERVICE_MANAGER_
diff --git a/src/server2/main/server2-main.cpp b/src/server2/main/server2-main.cpp
deleted file mode 100644 (file)
index df510ae..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        sever2-main.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of security-server2
- */
-
-#include <server2-main.h>
-
-#include <dpl/log/log.h>
-#include <dpl/singleton.h>
-#include <dpl/singleton_safe_impl.h>
-
-#include <service-thread.h>
-#include <socket-manager.h>
-
-#include <data-share.h>
-#include <get-gid.h>
-#include <privilege-by-pid.h>
-#include <get-object-name.h>
-#include <app-permissions.h>
-#include <cookie.h>
-#include <open-for.h>
-#include <password.h>
-#include <echo.h>
-
-IMPLEMENT_SAFE_SINGLETON(SecurityServer::Log::LogSystem);
-
-int server2(void) {
-    UNHANDLED_EXCEPTION_HANDLER_BEGIN
-    {
-        SecurityServer::Singleton<SecurityServer::Log::LogSystem>::Instance().SetTag("SECURITY_SERVER2");
-        LogInfo("Start!");
-        SecurityServer::SocketManager manager;
-
-//        This will be used only by tests
-//        SecurityServer::EchoService *echoService = new SecurityServer::EchoService;
-//        echoService->Create();
-//        manager.RegisterSocketService(echoService);
-
-
-        SecurityServer::OpenForService *openForService = new SecurityServer::OpenForService;
-        openForService->Create();
-        manager.RegisterSocketService(openForService);
-
-        SecurityServer::CookieService *cookieService = new SecurityServer::CookieService;
-        cookieService->Create();
-        manager.RegisterSocketService(cookieService);
-
-        SecurityServer::SharedMemoryService *shmService = new SecurityServer::SharedMemoryService;
-        shmService->Create();
-        manager.RegisterSocketService(shmService);
-
-        SecurityServer::GetGidService *getGidService = new SecurityServer::GetGidService;
-        getGidService->Create();
-        manager.RegisterSocketService(getGidService);
-
-        SecurityServer::PrivilegeByPidService *privByPidService = new SecurityServer::PrivilegeByPidService;
-        privByPidService->Create();
-        manager.RegisterSocketService(privByPidService);
-
-        SecurityServer::GetObjectNameService *getObjectNameService = new SecurityServer::GetObjectNameService;
-        getObjectNameService->Create();
-        manager.RegisterSocketService(getObjectNameService);
-
-        SecurityServer::AppPermissionsService *appEnablePermissionsService = new SecurityServer::AppPermissionsService;
-        appEnablePermissionsService->Create();
-        manager.RegisterSocketService(appEnablePermissionsService);
-
-        SecurityServer::PasswordService *pwdService = new SecurityServer::PasswordService;
-        pwdService->Create();
-        manager.RegisterSocketService(pwdService);
-
-        manager.MainLoop();
-    }
-    UNHANDLED_EXCEPTION_HANDLER_END
-    return 0;
-}
-
diff --git a/src/server2/main/server2-main.h b/src/server2/main/server2-main.h
deleted file mode 100644 (file)
index c5965a7..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        server-main2.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of security-server2.
- */
-
-#ifndef _SECURITY_SERVER_SERVER2_
-#define _SECURITY_SERVER_SERVER2_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int server2(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _SECURITY_SERVER_SERVER2_
-
diff --git a/src/server2/main/service-thread.h b/src/server2/main/service-thread.h
deleted file mode 100644 (file)
index e5989e6..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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-thread.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of threads.
- */
-
-#ifndef _SECURITY_SERVER_SERVICE_THREAD_
-#define _SECURITY_SERVER_SERVICE_THREAD_
-
-#include <cassert>
-#include <queue>
-#include <mutex>
-#include <thread>
-#include <memory>
-#include <condition_variable>
-
-#include <cstdio>
-
-#include <dpl/exception.h>
-
-#include "generic-event.h"
-
-#define DEFINE_THREAD_EVENT(eventType)                                \
-    void Event(const eventType &event) {                              \
-        SecurityServer::ServiceThread<ParentClassName>::              \
-            Event(event,                                              \
-                  this,                                               \
-                  &ParentClassName::EventInternal##eventType);        \
-    }                                                                 \
-    void EventInternal##eventType(const eventType &event)
-
-#define DECLARE_THREAD_EVENT(eventType, methodName)                   \
-    void Event(const eventType &event) {                              \
-        SecurityServer::ServiceThread<ParentClassName>::              \
-            Event(event,                                              \
-                  this,                                               \
-                  &ParentClassName::methodName);                      \
-    }
-
-namespace SecurityServer {
-
-template <class Service>
-class ServiceThread {
-public:
-    typedef Service ParentClassName;
-    enum class State {
-        NoThread,
-        Work,
-    };
-
-    ServiceThread()
-      : m_state(State::NoThread)
-      , m_quit(false)
-    {}
-
-    void Create() {
-        assert(m_state == State::NoThread);
-        m_thread = std::thread(ThreadLoopStatic, this);
-        m_state = State::Work;
-    }
-
-    void Join() {
-        assert(m_state != State::NoThread);
-        {
-            std::lock_guard<std::mutex> lock(m_eventQueueMutex);
-            m_quit = true;
-            m_waitCondition.notify_one();
-        }
-        m_thread.join();
-        m_state = State::NoThread;
-    }
-
-    virtual ~ServiceThread()
-    {
-        if (m_state != State::NoThread)
-            Join();
-        while (!m_eventQueue.empty()){
-            auto front = m_eventQueue.front();
-            delete front.eventPtr;
-            m_eventQueue.pop();
-        }
-    }
-
-    template <class T>
-    void Event(const T &event,
-               Service *servicePtr,
-               void (Service::*serviceFunction)(const T &))
-    {
-        EventDescription description;
-        description.serviceFunctionPtr =
-            reinterpret_cast<void (Service::*)(void*)>(serviceFunction);
-        description.servicePtr = servicePtr;
-        description.eventFunctionPtr = &ServiceThread::EventCall<T>;
-        description.eventPtr = new T(event);
-        {
-            std::lock_guard<std::mutex> lock(m_eventQueueMutex);
-            m_eventQueue.push(description);
-        }
-        m_waitCondition.notify_one();
-    }
-
-protected:
-
-    struct EventDescription {
-        void (Service::*serviceFunctionPtr)(void *);
-        Service *servicePtr;
-        void (ServiceThread::*eventFunctionPtr)(const EventDescription &event);
-        GenericEvent* eventPtr;
-    };
-
-    template <class T>
-    void EventCall(const EventDescription &desc) {
-        auto fun = reinterpret_cast<void (Service::*)(const T&)>(desc.serviceFunctionPtr);
-        const T& eventLocale = *(static_cast<T*>(desc.eventPtr));
-        (desc.servicePtr->*fun)(eventLocale);
-    }
-
-    static void ThreadLoopStatic(ServiceThread *ptr) {
-        ptr->ThreadLoop();
-    }
-
-    void ThreadLoop(){
-        for (;;) {
-            EventDescription description = {NULL, NULL, NULL, NULL};
-            {
-                std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
-                if (m_quit)
-                    return;
-                if (!m_eventQueue.empty()) {
-                    description = m_eventQueue.front();
-                    m_eventQueue.pop();
-                } else {
-                    m_waitCondition.wait(ulock);
-                }
-            }
-
-            if (description.eventPtr != NULL) {
-                UNHANDLED_EXCEPTION_HANDLER_BEGIN
-                {
-                    (this->*description.eventFunctionPtr)(description);
-                    delete description.eventPtr;
-                }
-                UNHANDLED_EXCEPTION_HANDLER_END
-            }
-        }
-    }
-
-    std::thread m_thread;
-    std::mutex m_eventQueueMutex;
-    std::queue<EventDescription> m_eventQueue;
-    std::condition_variable m_waitCondition;
-
-    State m_state;
-    bool m_quit;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_SERVICE_THREAD_
diff --git a/src/server2/main/socket-manager.cpp b/src/server2/main/socket-manager.cpp
deleted file mode 100644 (file)
index b62f840..0000000
+++ /dev/null
@@ -1,731 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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-manager.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of SocketManager.
- */
-
-#include <set>
-
-#include <signal.h>
-#include <sys/select.h>
-#include <sys/signalfd.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/smack.h>
-#include <sys/un.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <errno.h>
-#include <time.h>
-
-#include <systemd/sd-daemon.h>
-
-#include <dpl/log/log.h>
-#include <dpl/assert.h>
-
-#include <smack-check.h>
-#include <socket-manager.h>
-
-namespace {
-
-const time_t SOCKET_TIMEOUT = 20;
-
-} // namespace anonymous
-
-namespace SecurityServer {
-
-struct DummyService : public GenericSocketService {
-    ServiceDescriptionVector GetServiceDescription() {
-        return ServiceDescriptionVector();
-    }
-    void Event(const AcceptEvent &event) { (void)event; }
-    void Event(const WriteEvent &event) { (void)event; }
-    void Event(const ReadEvent &event) { (void)event; }
-    void Event(const CloseEvent &event) { (void)event; }
-};
-
-struct SignalService : public GenericSocketService {
-    int GetDescriptor() {
-        LogInfo("set up");
-        sigset_t mask;
-        sigemptyset(&mask);
-        sigaddset(&mask, SIGTERM);
-        if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL))
-            return -1;
-        return signalfd(-1, &mask, 0);
-    }
-
-    ServiceDescriptionVector GetServiceDescription() {
-        return ServiceDescriptionVector();
-    }
-
-    void Event(const AcceptEvent &event) { (void)event; } // not supported
-    void Event(const WriteEvent &event) { (void)event; }  // not supported
-    void Event(const CloseEvent &event) { (void)event; }  // not supported
-
-    void Event(const ReadEvent &event) {
-        LogDebug("Get signal information");
-
-        if(sizeof(struct signalfd_siginfo) != event.rawBuffer.size()) {
-            LogError("Wrong size of signalfd_siginfo struct. Expected: "
-                << sizeof(signalfd_siginfo) << " Get: "
-                << event.rawBuffer.size());
-            return;
-        }
-
-        signalfd_siginfo *siginfo = (signalfd_siginfo*)(&(event.rawBuffer[0]));
-
-        if (siginfo->ssi_signo == SIGTERM) {
-            LogInfo("Got signal: SIGTERM");
-            static_cast<SocketManager*>(m_serviceManager)->MainLoopStop();
-            return;
-        }
-
-        LogInfo("This should not happend. Got signal: " << siginfo->ssi_signo);
-    }
-};
-
-SocketManager::SocketDescription&
-SocketManager::CreateDefaultReadSocketDescription(int sock, bool timeout)
-{
-    if ((int)m_socketDescriptionVector.size() <= sock)
-        m_socketDescriptionVector.resize(sock+20);
-
-    auto &desc = m_socketDescriptionVector[sock];
-    desc.isListen = false;
-    desc.isOpen = true;
-    desc.interfaceID = 0;
-    desc.service = NULL;
-    desc.counter = ++m_counter;
-
-    if (timeout) {
-        desc.timeout = time(NULL) + SOCKET_TIMEOUT;
-        if (false == desc.isTimeout) {
-            Timeout tm;
-            tm.time = desc.timeout;
-            tm.sock = sock;
-            m_timeoutQueue.push(tm);
-        }
-    }
-
-    desc.isTimeout = timeout;
-
-    FD_SET(sock, &m_readSet);
-    m_maxDesc = sock > m_maxDesc ? sock : m_maxDesc;
-    return desc;
-}
-
-SocketManager::SocketManager()
-  : m_counter(0)
-{
-    FD_ZERO(&m_readSet);
-    FD_ZERO(&m_writeSet);
-    if (-1 == pipe(m_notifyMe)) {
-        int err = errno;
-        ThrowMsg(Exception::InitFailed, "Error in pipe: " << strerror(err));
-    }
-    LogInfo("Pipe: Read desc: " << m_notifyMe[0] << " Write desc: " << m_notifyMe[1]);
-
-    auto &desc = CreateDefaultReadSocketDescription(m_notifyMe[0], false);
-    desc.service = new DummyService;
-
-    // std::thread bases on pthread so this should work fine
-    sigset_t set;
-    sigemptyset(&set);
-    sigaddset(&set, SIGPIPE);
-    pthread_sigmask(SIG_BLOCK, &set, NULL);
-
-    // add support for TERM signal (passed from systemd)
-    auto *signalService = new SignalService;
-    signalService->SetSocketManager(this);
-    int filefd = signalService->GetDescriptor();
-    if (-1 == filefd) {
-        LogError("Error in SignalService.GetDescriptor()");
-        delete signalService;
-    } else {
-        auto &desc2 = CreateDefaultReadSocketDescription(filefd, false);
-        desc2.service = signalService;
-        LogInfo("SignalService mounted on " << filefd << " descriptor");
-    }
-}
-
-SocketManager::~SocketManager() {
-    std::set<GenericSocketService*> serviceMap;
-
-    // Find all services. Set is used to remove duplicates.
-    // In this implementation, services are not able to react in any way.
-    for (size_t i=0; i < m_socketDescriptionVector.size(); ++i)
-        if (m_socketDescriptionVector[i].isOpen)
-            serviceMap.insert(m_socketDescriptionVector[i].service);
-
-    // Time to destroy all services.
-    for(auto it = serviceMap.begin(); it != serviceMap.end(); ++it) {
-        LogDebug("delete " << (void*)(*it));
-        delete *it;
-    }
-
-    for (size_t i = 0; i < m_socketDescriptionVector.size(); ++i)
-        if (m_socketDescriptionVector[i].isOpen)
-            close(i);
-
-    // All socket except one were closed. Now pipe input must be closed.
-    close(m_notifyMe[1]);
-}
-
-void SocketManager::ReadyForAccept(int sock) {
-    struct sockaddr_un clientAddr;
-    unsigned int clientLen = sizeof(clientAddr);
-    int client = accept4(sock, (struct sockaddr*) &clientAddr, &clientLen, SOCK_NONBLOCK);
-//    LogInfo("Accept on sock: " << sock << " Socket opended: " << client);
-    if (-1 == client) {
-        int err = errno;
-        LogDebug("Error in accept: " << strerror(err));
-        return;
-    }
-
-    auto &desc = CreateDefaultReadSocketDescription(client, true);
-    desc.interfaceID = m_socketDescriptionVector[sock].interfaceID;
-    desc.service = m_socketDescriptionVector[sock].service;
-    desc.useSendMsg = m_socketDescriptionVector[sock].useSendMsg;
-
-    GenericSocketService::AcceptEvent event;
-    event.connectionID.sock = client;
-    event.connectionID.counter = desc.counter;
-    event.interfaceID = desc.interfaceID;
-    desc.service->Event(event);
-}
-
-void SocketManager::ReadyForRead(int sock) {
-    if (m_socketDescriptionVector[sock].isListen) {
-        ReadyForAccept(sock);
-        return;
-    }
-
-    GenericSocketService::ReadEvent event;
-    event.connectionID.sock = sock;
-    event.connectionID.counter = m_socketDescriptionVector[sock].counter;
-    event.rawBuffer.resize(4096);
-
-    auto &desc = m_socketDescriptionVector[sock];
-    desc.timeout = time(NULL) + SOCKET_TIMEOUT;
-
-    ssize_t size = read(sock, &event.rawBuffer[0], 4096);
-
-    if (size == 0) {
-        CloseSocket(sock);
-    } else if (size >= 0) {
-        event.rawBuffer.resize(size);
-        desc.service->Event(event);
-    } else if (size == -1) {
-        int err = errno;
-        switch(err) {
-            case EAGAIN:
-            case EINTR:
-                break;
-            default:
-                LogDebug("Reading sock error: " << strerror(err));
-                CloseSocket(sock);
-        }
-    }
-}
-
-void SocketManager::ReadyForSendMsg(int sock) {
-    auto &desc = m_socketDescriptionVector[sock];
-
-    if (desc.sendMsgDataQueue.empty()) {
-         FD_CLR(sock, &m_writeSet);
-         return;
-    }
-
-    auto data = desc.sendMsgDataQueue.front();
-    ssize_t result = sendmsg(sock, data.getMsghdr(), data.flags());
-
-    if (result == -1) {
-        int err = errno;
-        switch(err) {
-        case EAGAIN:
-        case EINTR:
-            break;
-        case EPIPE:
-        default:
-            LogDebug("Error during send: " << strerror(err));
-            CloseSocket(sock);
-            break;
-        }
-        return;
-    } else {
-        desc.sendMsgDataQueue.pop();
-    }
-
-    if (desc.sendMsgDataQueue.empty()) {
-        FD_CLR(sock, &m_writeSet);
-    }
-
-    desc.timeout = time(NULL) + SOCKET_TIMEOUT;
-
-    GenericSocketService::WriteEvent event;
-    event.connectionID.sock = sock;
-    event.connectionID.counter = desc.counter;
-    event.size = result;
-    event.left = desc.sendMsgDataQueue.size();
-
-    desc.service->Event(event);
-}
-
-void SocketManager::ReadyForWriteBuffer(int sock) {
-    auto &desc = m_socketDescriptionVector[sock];
-    size_t size = desc.rawBuffer.size();
-    ssize_t result = write(sock, &desc.rawBuffer[0], size);
-    if (result == -1) {
-        int err = errno;
-        switch(err) {
-        case EAGAIN:
-        case EINTR:
-            // select will trigger write once again, nothing to do
-            break;
-        case EPIPE:
-        default:
-            LogDebug("Error during write: " << strerror(err));
-            CloseSocket(sock);
-            break;
-        }
-        return; // We do not want to propagate error to next layer
-    }
-
-    desc.rawBuffer.erase(desc.rawBuffer.begin(), desc.rawBuffer.begin()+result);
-
-    desc.timeout = time(NULL) + SOCKET_TIMEOUT;
-
-    if (desc.rawBuffer.empty())
-        FD_CLR(sock, &m_writeSet);
-
-    GenericSocketService::WriteEvent event;
-    event.connectionID.sock = sock;
-    event.connectionID.counter = desc.counter;
-    event.size = result;
-    event.left = desc.rawBuffer.size();
-
-    desc.service->Event(event);
-}
-
-void SocketManager::ReadyForWrite(int sock) {
-    m_socketDescriptionVector[sock].useSendMsg ?
-        ReadyForSendMsg(sock) : ReadyForWriteBuffer(sock);
-}
-
-void SocketManager::MainLoop() {
-    // remove evironment values passed by systemd
-    // uncomment it after removing old security-server code
-    // sd_listen_fds(1);
-
-    // Daemon is ready to work.
-    sd_notify(0, "READY=1");
-
-    m_working = true;
-    while(m_working) {
-        fd_set readSet = m_readSet;
-        fd_set writeSet = m_writeSet;
-
-        timeval localTempTimeout;
-        timeval *ptrTimeout = &localTempTimeout;
-
-        // I need to extract timeout from priority_queue.
-        // Timeout in priority_queue may be deprecated.
-        // I need to find some actual one.
-        while(!m_timeoutQueue.empty()) {
-            auto &top = m_timeoutQueue.top();
-            auto &desc = m_socketDescriptionVector[top.sock];
-
-            if (top.time == desc.timeout) {
-                // This timeout matches timeout from socket.
-                // It can be used.
-                break;
-            } else {
-                // This socket was used after timeout in priority queue was set up.
-                // We need to update timeout and find some useable one.
-                Timeout tm = { desc.timeout , top.sock};
-                m_timeoutQueue.pop();
-                m_timeoutQueue.push(tm);
-            }
-        }
-
-        if (m_timeoutQueue.empty()) {
-            LogDebug("No usaable timeout found.");
-            ptrTimeout = NULL; // select will wait without timeout
-        } else {
-            time_t currentTime = time(NULL);
-            auto &pqTimeout = m_timeoutQueue.top();
-
-            // 0 means that select won't block and socket will be closed ;-)
-            ptrTimeout->tv_sec =
-              currentTime < pqTimeout.time ? pqTimeout.time - currentTime : 0;
-            ptrTimeout->tv_usec = 0;
-//            LogDebug("Set up timeout: " << (int)ptrTimeout->tv_sec
-//                << " seconds. Socket: " << pqTimeout.sock);
-        }
-
-        int ret = select(m_maxDesc+1, &readSet, &writeSet, NULL, ptrTimeout);
-
-        if (0 == ret) { // timeout
-            Assert(!m_timeoutQueue.empty());
-
-            Timeout pqTimeout = m_timeoutQueue.top();
-            m_timeoutQueue.pop();
-
-            auto &desc = m_socketDescriptionVector[pqTimeout.sock];
-
-            if (!desc.isTimeout || !desc.isOpen) {
-                // Connection was closed. Timeout is useless...
-                desc.isTimeout = false;
-                continue;
-            }
-
-            if (pqTimeout.time < desc.timeout) {
-                // Is it possible?
-                // This socket was used after timeout. We need to update timeout.
-                pqTimeout.time = desc.timeout;
-                m_timeoutQueue.push(pqTimeout);
-                continue;
-            }
-
-            // timeout from m_timeoutQueue matches with socket.timeout
-            // and connection is open. Time to close it!
-            // Putting new timeout in queue here is pointless.
-            desc.isTimeout = false;
-            CloseSocket(pqTimeout.sock);
-
-            // All done. Now we should process next select ;-)
-            continue;
-        }
-
-        if (-1 == ret) {
-            switch(errno) {
-            case EINTR:
-                LogDebug("EINTR in select");
-                break;
-            default:
-                int err = errno;
-                LogError("Error in select: " << strerror(err));
-                return;
-            }
-            continue;
-        }
-        for(int i = 0; i<m_maxDesc+1 && ret; ++i) {
-            if (FD_ISSET(i, &readSet)) {
-                ReadyForRead(i);
-                --ret;
-            }
-            if (FD_ISSET(i, &writeSet)) {
-                ReadyForWrite(i);
-                --ret;
-            }
-        }
-        ProcessQueue();
-    }
-}
-
-void SocketManager::MainLoopStop()
-{
-    m_working = false;
-    NotifyMe();
-}
-
-int SocketManager::GetSocketFromSystemD(
-    const GenericSocketService::ServiceDescription &desc)
-{
-    int fd;
-
-    // TODO optimalization - do it once in object constructor
-    //                       and remember all information path->sockfd
-    int n = sd_listen_fds(0);
-
-    LogInfo("sd_listen_fds returns: " << n);
-
-    if (n < 0) {
-        LogError("Error in sd_listend_fds");
-        ThrowMsg(Exception::InitFailed, "Error in sd_listend_fds");
-    }
-
-    for(fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) {
-        if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1,
-                                  desc.serviceHandlerPath.c_str(), 0))
-        {
-            LogInfo("Useable socket " << desc.serviceHandlerPath <<
-                " was passed by SystemD under descriptor " << fd);
-            return fd;
-        }
-    }
-    LogInfo("No useable sockets were passed by systemd.");
-    return -1;
-}
-
-int SocketManager::CreateDomainSocketHelp(
-    const GenericSocketService::ServiceDescription &desc)
-{
-    int sockfd;
-
-    if (-1 == (sockfd = socket(AF_UNIX, SOCK_STREAM, 0))) {
-        int err = errno;
-        LogError("Error in socket: " << strerror(err));
-        ThrowMsg(Exception::InitFailed, "Error in socket: " << strerror(err));
-    }
-
-    if (smack_check()) {
-        LogInfo("Set up smack label: " << desc.smackLabel);
-
-        if (0 != smack_fsetlabel(sockfd, desc.smackLabel.c_str(), SMACK_LABEL_IPIN)) {
-            LogError("Error in smack_fsetlabel");
-            ThrowMsg(Exception::InitFailed, "Error in smack_fsetlabel");
-        }
-    } else {
-        LogInfo("No smack on platform. Socket won't be securied with smack label!");
-    }
-
-    int flags;
-    if (-1 == (flags = fcntl(sockfd, F_GETFL, 0)))
-        flags = 0;
-
-    if (-1 == fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)) {
-        int err = errno;
-        close(sockfd);
-        LogError("Error in fcntl: " << strerror(err));
-        ThrowMsg(Exception::InitFailed, "Error in fcntl: " << strerror(err));
-    }
-
-    sockaddr_un serverAddress;
-    memset(&serverAddress, 0, sizeof(serverAddress));
-    serverAddress.sun_family = AF_UNIX;
-    strcpy(serverAddress.sun_path, desc.serviceHandlerPath.c_str());
-    unlink(serverAddress.sun_path);
-
-    mode_t originalUmask;
-    originalUmask = umask(0);
-
-    if (-1 == bind(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) {
-        int err = errno;
-        close(sockfd);
-        LogError("Error in bind: " << strerror(err));
-        ThrowMsg(Exception::InitFailed, "Error in bind: " << strerror(err));
-    }
-
-    umask(originalUmask);
-
-    if (-1 == listen(sockfd, 5)) {
-        int err = errno;
-        close(sockfd);
-        LogError("Error in listen: " << strerror(err));
-        ThrowMsg(Exception::InitFailed, "Error in listen: " << strerror(err));
-    }
-
-    return sockfd;
-}
-
-void SocketManager::CreateDomainSocket(
-    GenericSocketService *service,
-    const GenericSocketService::ServiceDescription &desc)
-{
-    int sockfd = GetSocketFromSystemD(desc);
-    if (-1 == sockfd)
-        sockfd = CreateDomainSocketHelp(desc);
-
-    auto &description = CreateDefaultReadSocketDescription(sockfd, false);
-
-    description.isListen = true;
-    description.interfaceID = desc.interfaceID;
-    description.useSendMsg = desc.useSendMsg;
-    description.service = service;
-
-    LogDebug("Listen on socket: " << sockfd <<
-        " Handler: " << desc.serviceHandlerPath.c_str());
-}
-
-void SocketManager::RegisterSocketService(GenericSocketService *service) {
-    service->SetSocketManager(this);
-    auto serviceVector = service->GetServiceDescription();
-    Try {
-        for (auto iter = serviceVector.begin(); iter != serviceVector.end(); ++iter)
-            CreateDomainSocket(service, *iter);
-    } Catch (Exception::Base) {
-        for (int i =0; i < (int)m_socketDescriptionVector.size(); ++i)
-        {
-            auto &desc = m_socketDescriptionVector[i];
-            if (desc.service == service && desc.isOpen) {
-                close(i);
-                desc.isOpen = false;
-            }
-        }
-        ReThrow(Exception::Base);
-    }
-}
-
-void SocketManager::Close(ConnectionID connectionID) {
-    {
-        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
-        m_closeQueue.push(connectionID);
-    }
-    NotifyMe();
-}
-
-void SocketManager::Write(ConnectionID connectionID, const RawBuffer &rawBuffer) {
-    WriteBuffer buffer;
-    buffer.connectionID = connectionID;
-    buffer.rawBuffer = rawBuffer;
-    {
-        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
-        m_writeBufferQueue.push(buffer);
-    }
-    NotifyMe();
-}
-
-void SocketManager::Write(ConnectionID connectionID, const SendMsgData &sendMsgData) {
-    WriteData data;
-    data.connectionID = connectionID;
-    data.sendMsgData = sendMsgData;
-    {
-        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
-        m_writeDataQueue.push(data);
-    }
-    NotifyMe();
-}
-
-void SocketManager::NotifyMe() {
-    TEMP_FAILURE_RETRY(write(m_notifyMe[1], "You have message ;-)", 1));
-}
-
-void SocketManager::ProcessQueue() {
-    WriteBuffer buffer;
-    WriteData data;
-    {
-        std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
-        while (!m_writeBufferQueue.empty()) {
-            buffer = m_writeBufferQueue.front();
-            m_writeBufferQueue.pop();
-
-            auto &desc = m_socketDescriptionVector[buffer.connectionID.sock];
-
-            if (!desc.isOpen) {
-                LogDebug("Received packet for write but connection is closed. Packet ignored!");
-                continue;
-            }
-
-            if (desc.counter != buffer.connectionID.counter)
-            {
-                LogDebug("Received packet for write but counter is broken. Packet ignored!");
-                continue;
-            }
-
-            if (desc.useSendMsg) {
-                LogError("Some service tried to push rawdata to socket that usees sendmsg!");
-                continue;
-            }
-
-            std::copy(
-                buffer.rawBuffer.begin(),
-                buffer.rawBuffer.end(),
-                std::back_inserter(desc.rawBuffer));
-
-            FD_SET(buffer.connectionID.sock, &m_writeSet);
-        }
-
-        while(!m_writeDataQueue.empty()) {
-            data = m_writeDataQueue.front();
-            m_writeDataQueue.pop();
-
-            auto &desc = m_socketDescriptionVector[data.connectionID.sock];
-
-            if (!desc.isOpen) {
-                LogDebug("Received packet for sendmsg but connection is closed. Packet ignored!");
-                continue;
-            }
-
-            if (desc.counter != data.connectionID.counter)
-            {
-                LogDebug("Received packet for write but counter is broken. Packet ignored!");
-                continue;
-            }
-
-            if (!desc.useSendMsg) {
-                LogError("Some service tries to push SendMsgData to socket that uses write!");
-                continue;
-            }
-
-            desc.sendMsgDataQueue.push(data.sendMsgData);
-
-            FD_SET(data.connectionID.sock, &m_writeSet);
-        }
-    }
-
-    while (1) {
-        ConnectionID connection;
-        {
-            std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
-            if (m_closeQueue.empty())
-                return;
-            connection = m_closeQueue.front();
-            m_closeQueue.pop();
-        }
-
-        if (!m_socketDescriptionVector[connection.sock].isOpen)
-            continue;
-
-        if (connection.counter != m_socketDescriptionVector[connection.sock].counter)
-            continue;
-
-        CloseSocket(connection.sock);
-    }
-}
-
-void SocketManager::CloseSocket(int sock) {
-//    LogInfo("Closing socket: " << sock);
-    auto &desc = m_socketDescriptionVector[sock];
-
-    if (!(desc.isOpen)) {
-        // This may happend when some information was waiting for write to the
-        // socket and in the same time socket was closed by the client.
-        LogError("Socket " << sock << " is not open. Nothing to do!");
-        return;
-    }
-
-    GenericSocketService::CloseEvent event;
-    event.connectionID.sock = sock;
-    event.connectionID.counter = desc.counter;
-    auto service = desc.service;
-
-    desc.isOpen = false;
-    desc.service = NULL;
-    desc.interfaceID = -1;
-    desc.rawBuffer.clear();
-    while(!desc.sendMsgDataQueue.empty())
-        desc.sendMsgDataQueue.pop();
-
-    if (service)
-        service->Event(event);
-    else
-        LogError("Critical! Service is NULL! This should never happend!");
-
-    TEMP_FAILURE_RETRY(close(sock));
-    FD_CLR(sock, &m_readSet);
-    FD_CLR(sock, &m_writeSet);
-}
-
-} // namespace SecurityServer
diff --git a/src/server2/main/socket-manager.h b/src/server2/main/socket-manager.h
deleted file mode 100644 (file)
index b7b733c..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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-manager.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       SocketManager implementation.
- */
-
-#ifndef _SECURITY_SERVER_SOCKET_MANAGER_
-#define _SECURITY_SERVER_SOCKET_MANAGER_
-
-#include <vector>
-#include <queue>
-#include <string>
-#include <mutex>
-#include <thread>
-
-#include <dpl/exception.h>
-
-#include <generic-socket-manager.h>
-
-namespace SecurityServer {
-
-class SocketManager : public GenericSocketManager {
-public:
-    class Exception {
-    public:
-        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
-        DECLARE_EXCEPTION_TYPE(Base, InitFailed)
-    };
-    SocketManager();
-    virtual ~SocketManager();
-    virtual void MainLoop();
-    virtual void MainLoopStop();
-
-    virtual void RegisterSocketService(GenericSocketService *service);
-    virtual void Close(ConnectionID connectionID);
-    virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer);
-    virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData);
-
-protected:
-    void CreateDomainSocket(
-        GenericSocketService *service,
-        const GenericSocketService::ServiceDescription &desc);
-    int CreateDomainSocketHelp(
-        const GenericSocketService::ServiceDescription &desc);
-    int GetSocketFromSystemD(
-        const GenericSocketService::ServiceDescription &desc);
-
-    void ReadyForRead(int sock);
-    void ReadyForWrite(int sock);
-    void ReadyForWriteBuffer(int sock);
-    void ReadyForSendMsg(int sock);
-    void ReadyForAccept(int sock);
-    void ProcessQueue(void);
-    void NotifyMe(void);
-    void CloseSocket(int sock);
-
-    struct SocketDescription {
-        bool isListen;
-        bool isOpen;
-        bool isTimeout;
-        bool useSendMsg;
-        InterfaceID interfaceID;
-        GenericSocketService *service;
-        time_t timeout;
-        RawBuffer rawBuffer;
-        std::queue<SendMsgData> sendMsgDataQueue;
-        int counter;
-
-        SocketDescription()
-          : isListen(false)
-          , isOpen(false)
-          , isTimeout(false)
-          , useSendMsg(false)
-          , interfaceID(-1)
-          , service(NULL)
-        {}
-    };
-
-    SocketDescription& CreateDefaultReadSocketDescription(int sock, bool timeout);
-
-    typedef std::vector<SocketDescription> SocketDescriptionVector;
-
-    struct WriteBuffer {
-        ConnectionID connectionID;
-        RawBuffer rawBuffer;
-    };
-
-    struct WriteData {
-        ConnectionID connectionID;
-        SendMsgData sendMsgData;
-    };
-
-    struct Timeout {
-        time_t time;
-        int sock;
-        bool operator<(const Timeout &second) const {
-            return time > second.time; // mininum first!
-        }
-    };
-
-    SocketDescriptionVector m_socketDescriptionVector;
-    fd_set m_readSet;
-    fd_set m_writeSet;
-    int m_maxDesc;
-    bool m_working;
-    std::mutex m_eventQueueMutex;
-    std::queue<WriteBuffer> m_writeBufferQueue;
-    std::queue<WriteData> m_writeDataQueue;
-    std::queue<ConnectionID> m_closeQueue;
-    int m_notifyMe[2];
-    int m_counter;
-    std::priority_queue<Timeout> m_timeoutQueue;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_SOCKET_MANAGER_
diff --git a/src/server2/service/app-permissions.cpp b/src/server2/service/app-permissions.cpp
deleted file mode 100644 (file)
index 290650d..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        app-permissions.cpp
- * @author      Pawel Polawski (pawel.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This function contain implementation of security_server_app_enable_permissions
- *              and security_server_app_disable_permissions on server side
- */
-
-#include <memory>
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-#include <privilege-control.h>
-
-#include <sys/smack.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <app-permissions.h>
-#include <protocols.h>
-#include <security-server.h>
-#include <security-server-common.h>
-
-namespace SecurityServer {
-
-namespace {
-
-int privilegeToSecurityServerError(int error) {
-    switch (error) {
-    case PC_OPERATION_SUCCESS:  return SECURITY_SERVER_API_SUCCESS;
-    case PC_ERR_FILE_OPERATION: return SECURITY_SERVER_API_ERROR_UNKNOWN;
-    case PC_ERR_MEM_OPERATION:  return SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
-    case PC_ERR_NOT_PERMITTED:  return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
-    case PC_ERR_INVALID_PARAM:  return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-    case PC_ERR_INVALID_OPERATION:
-    case PC_ERR_DB_OPERATION:
-    default:
-        ;
-    }
-    return SECURITY_SERVER_API_ERROR_UNKNOWN;
-}
-
-// interface ids
-const InterfaceID CHANGE_APP_PERMISSIONS = 0;
-const InterfaceID CHECK_APP_PRIVILEGE = 1;
-
-} // namespace anonymous
-
-GenericSocketService::ServiceDescriptionVector AppPermissionsService::GetServiceDescription() {
-    return ServiceDescriptionVector {
-        { SERVICE_SOCKET_APP_PERMISSIONS,
-          "security-server::api-app-permissions",
-          CHANGE_APP_PERMISSIONS },
-        { SERVICE_SOCKET_APP_PRIVILEGE_BY_NAME,
-          "security-server::api-app-privilege-by-name",
-          CHECK_APP_PRIVILEGE }
-    };
-}
-
-void AppPermissionsService::accept(const AcceptEvent &event) {
-    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-    auto &info = m_connectionInfoMap[event.connectionID.counter];
-    info.interfaceID = event.interfaceID;
-}
-
-void AppPermissionsService::write(const WriteEvent &event) {
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-void AppPermissionsService::process(const ReadEvent &event) {
-    LogDebug("Read event for counter: " << event.connectionID.counter);
-    auto &info = m_connectionInfoMap[event.connectionID.counter];
-    info.buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, info.buffer, info.interfaceID));
-}
-
-void AppPermissionsService::close(const CloseEvent &event) {
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    m_connectionInfoMap.erase(event.connectionID.counter);
-}
-
-bool AppPermissionsService::processOne(const ConnectionID &conn,
-                                       MessageBuffer &buffer,
-                                       InterfaceID interfaceID)
-{
-    LogDebug("Iteration begin");
-
-    //waiting for all data
-    if (!buffer.Ready()) {
-        return false;
-    }
-
-    LogDebug("Entering app_permissions server side handler");
-
-    switch(interfaceID) {
-    case CHANGE_APP_PERMISSIONS:
-        return processPermissionsChange(conn, buffer);
-
-    case CHECK_APP_PRIVILEGE:
-        return processCheckAppPrivilege(conn, buffer);
-
-    default:
-        LogDebug("Unknown interfaceId. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-}
-
-bool AppPermissionsService::processPermissionsChange(const ConnectionID &conn, MessageBuffer &buffer)
-{
-    MessageBuffer send;
-    std::vector<std::string> permissions_list;
-    std::string app_id;
-    int persistent;
-    size_t iter;
-    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-    app_type_t app_type;
-    AppPermissionsAction appPermAction;
-
-    LogDebug("Processing permissions change request");
-
-    //receive data from buffer and check MSG_ID
-    Try {
-        int temp;
-        Deserialization::Deserialize(buffer, temp);                 //receive MSG_ID
-        appPermAction = (AppPermissionsAction)temp;
-
-        if (appPermAction == AppPermissionsAction::ENABLE)      //persistent is only in APP_ENABLE frame
-            Deserialization::Deserialize(buffer, persistent);
-
-        Deserialization::Deserialize(buffer, temp);
-        app_type = (app_type_t)temp;
-        Deserialization::Deserialize(buffer, app_id);
-        Deserialization::Deserialize(buffer, permissions_list);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    //+1 bellow is for NULL pointer at the end
-    std::unique_ptr<const char *[]> perm_list (new (std::nothrow) const char *[permissions_list.size() + 1]);
-    if (NULL == perm_list.get()) {
-        LogError("Allocation error");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    //print received data
-    LogDebug("app_type: " << (int)app_type);
-    if (appPermAction == AppPermissionsAction::ENABLE)    //persistent is only in APP_ENABLE frame
-        LogDebug("persistent: " << persistent);
-    LogDebug("app_id: " << app_id);
-
-    //left one free pointer for the NULL at the end
-    for (iter = 0; iter < permissions_list.size(); ++iter) {
-        LogDebug("perm_list[" << iter << "]: " << permissions_list[iter]);
-        perm_list[iter] = (permissions_list[iter]).c_str();
-    }
-    //put the NULL at the end
-    perm_list[iter] = NULL;
-
-    //use received data
-    if (appPermAction == AppPermissionsAction::ENABLE) {
-        LogDebug("Calling perm_app_enable_permissions()");
-        result = perm_app_enable_permissions(app_id.c_str(), app_type, perm_list.get(), persistent);
-        LogDebug("perm_app_enable_permissions() returned: " << result);
-    } else {
-        LogDebug("Calling perm_app_disable_permissions()");
-        result = perm_app_disable_permissions(app_id.c_str(), app_type, perm_list.get());
-        LogDebug("perm_app_disable_permissions() returned: " << result);
-    }
-
-    //send response
-    Serialization::Serialize(send, privilegeToSecurityServerError(result));
-    m_serviceManager->Write(conn, send.Pop());
-    return true;
-}
-
-bool AppPermissionsService::processCheckAppPrivilege(const ConnectionID &conn, MessageBuffer &buffer)
-{
-    MessageBuffer send;
-    std::string privilege_name;
-    std::string app_id;
-    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-    app_type_t app_type;
-    bool has_permission = false;
-    PrivilegeCheckHdrs checkType = PrivilegeCheckHdrs::CHECK_GIVEN_APP;
-
-    LogDebug("Processing app privilege check request");
-
-    //receive data from buffer
-    Try {
-        int temp;
-        Deserialization::Deserialize(buffer, temp); // call type
-        checkType = static_cast<PrivilegeCheckHdrs>(temp);
-        LogDebug("App privilege check call type: "
-                 << (checkType == PrivilegeCheckHdrs::CHECK_GIVEN_APP ?
-                     "CHECK_GIVEN_APP":"CHECK_CALLER_APP"));
-        if (checkType == PrivilegeCheckHdrs::CHECK_GIVEN_APP) { //app_id present only in this case
-            Deserialization::Deserialize(buffer, app_id); //get app id
-        }
-        Deserialization::Deserialize(buffer, temp); //get app type
-        app_type = static_cast<app_type_t>(temp);
-
-        Deserialization::Deserialize(buffer, privilege_name); //get privilege name
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    if (checkType == PrivilegeCheckHdrs::CHECK_CALLER_APP) { //get sender app_id in this case
-        char *label = NULL;
-        if (smack_new_label_from_socket(conn.sock, &label) < 0) {
-            LogDebug("Error in smack_new_label_from_socket(): "
-                     "client label is unknown. Sending error response.");
-            Serialization::Serialize(send, SECURITY_SERVER_API_ERROR_GETTING_SOCKET_LABEL_FAILED);
-            m_serviceManager->Write(conn, send.Pop());
-            return false;
-        } else {
-            app_id = label;
-            free(label);
-        }
-    } //end if
-
-    //print received data
-    LogDebug("app_id: " << app_id);
-    LogDebug("app_type: " << static_cast<int>(app_type));
-    LogDebug("privilege_name: " << privilege_name);
-
-    LogDebug("Calling perm_app_has_permission()");
-    result = perm_app_has_permission(app_id.c_str(), app_type, privilege_name.c_str(), &has_permission);
-    LogDebug("perm_app_has_permission() returned: " << result << " , permission enabled: " << has_permission);
-
-    //send response
-    Serialization::Serialize(send, privilegeToSecurityServerError(result));
-    Serialization::Serialize(send, static_cast<int>(has_permission));
-    m_serviceManager->Write(conn, send.Pop());
-    return true;
-}
-
-} // namespace SecurityServer
diff --git a/src/server2/service/app-permissions.h b/src/server2/service/app-permissions.h
deleted file mode 100644 (file)
index c445198..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        app-permissions.h
- * @author      Pawel Polawski (p.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This function contain header for implementation of security_server_app_enable_permissions
- *              and SS_app_disable_permissions on server side
- */
-
-#ifndef _SECURITY_SERVER_APP_PERMISSIONS_
-#define _SECURITY_SERVER_APP_PERMISSIONS_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-#include <dpl/serialization.h>
-#include <message-buffer.h>
-#include <connection-info.h>
-#include <security-server-common.h>
-
-namespace SecurityServer {
-
-class AppPermissionsService  :
-    public SecurityServer::GenericSocketService
-  , public SecurityServer::ServiceThread<AppPermissionsService>
-{
-public:
-    ServiceDescriptionVector GetServiceDescription();
-
-    DECLARE_THREAD_EVENT(AcceptEvent, accept)
-    DECLARE_THREAD_EVENT(WriteEvent, write)
-    DECLARE_THREAD_EVENT(ReadEvent, process)
-    DECLARE_THREAD_EVENT(CloseEvent, close)
-
-    void accept(const AcceptEvent &event);
-    void write(const WriteEvent &event);
-    void process(const ReadEvent &event);
-    void close(const CloseEvent &event);
-
-private:
-    bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
-
-    bool processPermissionsChange(const ConnectionID &conn, MessageBuffer &buffer);
-    bool processCheckAppPrivilege(const ConnectionID &conn, MessageBuffer &buffer);
-
-    ConnectionInfoMap m_connectionInfoMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_APP_ENABLE_PERMISSIONS_
diff --git a/src/server2/service/cookie-jar.cpp b/src/server2/service/cookie-jar.cpp
deleted file mode 100644 (file)
index 2e0e42b..0000000
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        cookie-jar.cpp
- * @author      Pawel Polawski (p.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This function contain implementation of CookieJar class which holds cookies structures
- */
-
-#include <cookie-jar.h>
-#include <protocols.h>
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-#include <vector>
-#include <stdbool.h>
-#include <unistd.h>
-#include <smack-check.h>
-#include <privilege-control.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/smack.h>
-#include <fstream>
-#include <linux/limits.h>
-#include <signal.h>
-#include <errno.h>
-
-namespace SecurityServer {
-
-CookieJar::CookieJar(void)
-  : m_position(0)
-{
-    LogDebug("Created CookieJar for handling cookies");
-}
-
-CookieJar::~CookieJar(void)
-{
-    LogDebug("Deleted CookieJar");
-}
-
-const Cookie * CookieJar::GenerateCookie(int pid)
-{
-    char key[COOKIE_SIZE];
-    int retval;
-
-    LogDebug("Cookie creation called");
-
-    //create empty cookie class
-    Cookie newCookie;
-    newCookie.pid = pid;
-
-    //check if there is no cookie for specified PID
-    const Cookie *searchResult = SearchCookie(newCookie, CompareType::PID);
-    if (searchResult != NULL) {
-        LogDebug("Cookie exist for specified PID");
-        return searchResult;
-    }
-
-    searchResult = &newCookie;   //only for searchResult != NULL
-    while(searchResult != NULL) {
-        //generate unique key
-        std::ifstream urandom("/dev/urandom", std::ifstream::binary);
-        urandom.read(key, COOKIE_SIZE);
-        newCookie.cookieId.assign(key, key + COOKIE_SIZE);
-
-        //check if key is unique
-        searchResult = SearchCookie(newCookie, CompareType::COOKIE_ID);
-        if (searchResult != NULL)
-            LogDebug("Key is not unique");
-    }
-
-    //obtain process path
-    char link[PATH_MAX];
-    char path[PATH_MAX];
-
-    snprintf(link, PATH_MAX, "/proc/%d/exe", pid);
-    retval = readlink(link, path, PATH_MAX-1);
-    if (retval < 0) {
-        LogDebug("Unable to get process path");
-        return NULL;
-    }
-    path[retval] = '\0';
-    newCookie.binaryPath = path;
-
-    //get smack label if smack enabled
-    if (smack_check()) {
-        char label[SMACK_LABEL_LEN + 1];
-        retval = get_smack_label_from_process(pid, label);
-        if (retval != PC_OPERATION_SUCCESS) {
-            LogDebug("Unable to get smack label of process");
-            return NULL;
-        }
-        newCookie.smackLabel = label;
-    } else
-        newCookie.smackLabel = "";
-
-
-    //get GID list
-    const int NAME_SIZE = 64;
-    char filename[NAME_SIZE];
-
-    snprintf(filename, NAME_SIZE, "/proc/%d/status", pid);
-    std::ifstream status(filename, std::ifstream::binary);
-    std::string line;
-
-    while (std::getline(status, line)) {  //read line from file
-        const char *tmp = line.c_str();
-        if (strncmp(line.c_str(), "Uid:", 4) == 0)
-            newCookie.uid = atoi(&tmp[5]);
-        else if (strncmp(line.c_str(), "Gid:", 4) == 0)
-            newCookie.gid = atoi(&tmp[5]);
-        else if (strncmp(line.c_str(), "Groups:", 7) == 0) {
-            char delim[] = ": ";    //separators for strtok: ' ' and ':'
-            char *token = strtok(const_cast<char *>(tmp), delim);  //1st string is "Group:"
-            while ((token = strtok(NULL, delim))) {
-                int gid = atoi(token);
-                newCookie.permissions.push_back(gid);
-            }
-        }
-    }
-
-    //DEBUG ONLY
-    //print info about cookie
-    LogDebug("Cookie created");
-    LogDebug("PID: " << newCookie.pid);
-    LogDebug("UID: " << newCookie.uid);
-    LogDebug("GID: " << newCookie.gid);
-    LogDebug("PATH: " << newCookie.binaryPath);
-    LogDebug("LABEL: " << newCookie.smackLabel);
-    for (size_t k = 0; k < newCookie.permissions.size(); k++)
-        LogDebug("GID: " << newCookie.permissions[k]);
-
-    m_cookieList.push_back(newCookie);
-    return &m_cookieList[m_cookieList.size() - 1];
-}
-
-void CookieJar::DeleteCookie(const Cookie &pattern, CompareType criterion)
-{
-    if (m_cookieList.size() == 0) {
-        LogDebug("Cookie list empty");
-        return;
-    }
-
-    //for each cookie in list
-    for (size_t i = 0; i < m_cookieList.size();) {
-        if (CompareCookies(pattern, m_cookieList[i], criterion)) {
-            LogDebug("Deleting cookie");
-            if (i != m_cookieList.size() - 1)
-                m_cookieList[i] = *m_cookieList.rbegin();
-            m_cookieList.pop_back();
-        } else
-            ++i;
-    }
-}
-
-const Cookie * CookieJar::SearchCookie(const Cookie &pattern, CompareType criterion) const
-{
-    LogDebug("Searching for cookie");
-
-    if (m_cookieList.size() == 0) {
-        LogDebug("Cookie list empty");
-        return NULL;
-    }
-
-    //for each cookie in list
-    for (size_t i = 0; i < m_cookieList.size(); i++) {
-        if (CompareCookies(pattern, m_cookieList[i], criterion)) {
-            LogDebug("Cookie found");
-            return &(m_cookieList[i]);
-        }
-    }
-
-    LogDebug("Cookie not found");
-    return NULL;
-}
-
-bool CookieJar::CompareCookies(const Cookie &c1, const Cookie &c2, CompareType criterion) const
-{
-    size_t permSize1 = c1.permissions.size();
-    size_t permSize2 = c2.permissions.size();
-
-    switch(criterion) {
-    case CompareType::COOKIE_ID:
-        return (c1.cookieId == c2.cookieId);
-
-    case CompareType::PID:
-        return (c1.pid == c2.pid);
-
-    case CompareType::PATH:
-        return (c1.binaryPath == c2.binaryPath);
-
-    case CompareType::SMACKLABEL:
-        return (c1.smackLabel == c2.smackLabel);
-
-    case CompareType::PERMISSIONS:
-        //we search for at least one the same GID
-        for(size_t i = 0; i < permSize1; i++)
-            for (size_t k = 0; k < permSize2; k++)
-                if (c1.permissions[i] == c2.permissions[k])
-                    return true;
-        return false;
-
-    case CompareType::UID:
-        return (c1.uid == c2.uid);
-
-    case CompareType::GID:
-        return (c1.gid == c2.gid);
-
-    default:
-        LogDebug("Wrong function parameters");
-        return false;
-    };
-}
-
-void CookieJar::GarbageCollector(size_t howMany)
-{
-    if ((howMany == 0) || (howMany > m_cookieList.size())) {
-        howMany = m_cookieList.size();
-    }
-
-    for (size_t i = 0; i < howMany; ++i) {
-
-        if (m_position >= m_cookieList.size()) {
-            m_position = 0;
-        }
-
-        if (kill(m_cookieList[m_position].pid, 0) && (errno == ESRCH)) {
-            LogDebug("Cookie deleted " << " PID:" << m_cookieList[m_position].pid);
-            if (m_position != (m_cookieList.size()-1))
-                m_cookieList[m_position] = *m_cookieList.rbegin();
-            m_cookieList.pop_back();
-        } else {
-            ++m_position;
-        }
-    }
-}
-
-} // namespace SecurityServer
diff --git a/src/server2/service/cookie-jar.h b/src/server2/service/cookie-jar.h
deleted file mode 100644 (file)
index 1f81c7a..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        cookie-jar.h
- * @author      Pawel Polawski (p.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This function contain header of CookieJar class which holds cookies structures
- */
-
-#ifndef _SECURITY_SERVER_COOKIE_JAR_
-#define _SECURITY_SERVER_COOKIE_JAR_
-
-#include <stdio.h>
-
-#include <dpl/log/log.h>
-#include <dpl/exception.h>
-#include <vector>
-#include <stdbool.h>
-
-
-namespace SecurityServer {
-
-enum class CompareType
-{
-    COOKIE_ID,
-    PID,
-    PATH,
-    SMACKLABEL,
-    PERMISSIONS,
-    UID,
-    GID
-};
-
-
-struct Cookie
-{
-    std::vector<char> cookieId;     //ID key
-    pid_t pid;                      //owner PID
-    uid_t uid;                      //owner UID
-    gid_t gid;                      //owner GID
-    std::string binaryPath;         //path to owner binary
-    std::string smackLabel;         //owner SMACK label
-    std::vector<int> permissions;   //owner GIDs
-};
-
-
-class CookieJar
-{
-public:
-    CookieJar(void);
-    virtual ~CookieJar(void);
-
-    const Cookie * GenerateCookie(int pid);
-    void DeleteCookie(const Cookie &pattern, CompareType criterion);
-
-    const Cookie * SearchCookie(const Cookie &pattern, CompareType criterion) const;
-    bool CompareCookies(const Cookie &c1, const Cookie &c2, CompareType criterion) const;
-
-    // howMany - number of cookies that will be checked.
-    // Set howMay to 0 to check all cookies.
-    void GarbageCollector(size_t howMany);
-
-private:
-    size_t m_position;
-    std::vector<Cookie> m_cookieList;
-};
-
-
-} // namespace SecurityServer
-#endif // _SECURITY_SERVER_COOKIE_JAR_
diff --git a/src/server2/service/cookie.cpp b/src/server2/service/cookie.cpp
deleted file mode 100644 (file)
index 7659dbd..0000000
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        cookie.cpp
- * @author      Pawel Polawski (p.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This function contain implementation of CookieService
- */
-
-#include <memory>
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-#include <protocols.h>
-#include <security-server.h>
-#include <security-server-common.h>
-#include <cookie.h>
-#include <smack-check.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/smack.h>
-
-//interfaces ID
-const int INTERFACE_GET = 0;
-const int INTERFACE_CHECK = 1;
-const int INTERFACE_CHECK_TMP = 3;
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector CookieService::GetServiceDescription() {
-    return ServiceDescriptionVector {
-        {SERVICE_SOCKET_COOKIE_GET,       "security-server::api-cookie-get",   INTERFACE_GET },
-        {SERVICE_SOCKET_COOKIE_CHECK,     "security-server::api-cookie-check", INTERFACE_CHECK},
-        {SERVICE_SOCKET_COOKIE_CHECK_TMP, "security-server::api-cookie-check", INTERFACE_CHECK_TMP}
-    };
- }
-
-void CookieService::accept(const AcceptEvent &event) {
-    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-    auto &info = m_connectionInfoMap[event.connectionID.counter];
-    info.interfaceID = event.interfaceID;
-}
-
-void CookieService::write(const WriteEvent &event) {
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-void CookieService::process(const ReadEvent &event) {
-    LogDebug("Read event for counter: " << event.connectionID.counter);
-    auto &info = m_connectionInfoMap[event.connectionID.counter];
-    info.buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, info.buffer, info.interfaceID));
-}
-
-void CookieService::close(const CloseEvent &event) {
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    m_connectionInfoMap.erase(event.connectionID.counter);
-}
-
-bool CookieService::processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID)
-{
-    LogDebug("Iteration begin");
-    MessageBuffer send, recv;
-    CookieCall msgType;
-    bool removeGarbage = false;
-
-    //waiting for all data
-    if (!buffer.Ready()) {
-        return false;
-    }
-
-    //receive data from buffer and check MSG_ID
-    Try {
-        int msgTypeInt;
-        Deserialization::Deserialize(buffer, msgTypeInt);  //receive MSG_ID
-        msgType = static_cast<CookieCall>(msgTypeInt);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    bool retval = false;
-
-    //use received data
-    if (interfaceID == INTERFACE_GET) {
-        switch(msgType) {
-        case CookieCall::GET_COOKIE:
-            LogDebug("Entering get-cookie server side handler");
-            retval = cookieRequest(send, conn.sock);
-            removeGarbage = true;
-            break;
-
-        default:
-            LogDebug("Error, unknown function called by client");
-            retval = false;
-            break;
-        };
-    } else if (interfaceID == INTERFACE_CHECK) {
-        switch(msgType) {
-        case CookieCall::CHECK_PID:
-            LogDebug("Entering pid-by-cookie server side handler");
-            retval = pidByCookieRequest(buffer, send);
-            break;
-
-        case CookieCall::CHECK_SMACKLABEL:
-            LogDebug("Entering smacklabel-by-cookie server side handler");
-            retval = smackLabelByCookieRequest(buffer, send);
-            break;
-
-        case CookieCall::CHECK_PRIVILEGE_GID:
-            LogDebug("Entering check-privilege-by-cookie-gid server side handler");
-            retval = privilegeByCookieGidRequest(buffer, send);
-            break;
-
-        case CookieCall::CHECK_PRIVILEGE:
-            LogDebug("Entering check-privilege-by-cookie side handler");
-            retval = privilegeByCookieRequest(buffer, send);
-            break;
-
-        default:
-            LogDebug("Error, unknown function called by client");
-            retval = false;
-            break;
-        };
-    } else if (interfaceID == INTERFACE_CHECK_TMP) {
-        //TODO: Merge this interface with INTERFACE_CHECK after INTERFACE_CHECK will be secured by smack 
-        switch(msgType) {
-        case CookieCall::CHECK_UID:
-            LogDebug("Entering get-uid-by-cookie side handler");
-            retval = uidByCookieRequest(buffer, send);
-            break;
-
-        case CookieCall::CHECK_GID:
-            LogDebug("Entering get-gid-by-cookie side handler");
-            retval = gidByCookieRequest(buffer, send);
-            break;
-
-        default:
-            LogDebug("Error, unknown function called by client");
-            retval = false;
-            break;
-        };
-    } else {
-        LogDebug("Error, wrong interface");
-        retval = false;
-    }
-
-    if (retval) {
-        //send response
-        m_serviceManager->Write(conn, send.Pop());
-    } else {
-        LogDebug("Closing socket because of error");
-        m_serviceManager->Close(conn);
-    }
-
-    // Each time you add one cookie check 2 others.
-    if (removeGarbage)
-        m_cookieJar.GarbageCollector(2);
-
-    return retval;
-}
-
-bool CookieService::cookieRequest(MessageBuffer &send, int socket)
-{
-    struct ucred cr;
-    unsigned len = sizeof(cr);
-
-    if (0 != getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &cr, &len))
-        return false;
-
-    const Cookie *generatedCookie = m_cookieJar.GenerateCookie(cr.pid);
-    if (generatedCookie != NULL) {
-        //cookie created correct
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-        Serialization::Serialize(send, generatedCookie->cookieId);
-    } else {
-        //unable to create cookie
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_UNKNOWN);
-    }
-
-    return true;
-}
-
-bool CookieService::pidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
-    std::vector<char> cookieKey;
-
-    Try {
-        Deserialization::Deserialize(buffer, cookieKey);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        return false;
-    }
-
-    Cookie searchPattern;
-    searchPattern.cookieId = cookieKey;
-
-    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
-    if (searchResult != NULL) {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-        Serialization::Serialize(send, (int)searchResult->pid);
-    } else {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
-    }
-
-    return true;
-}
-
-bool CookieService::smackLabelByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
-    std::vector<char> cookieKey;
-
-    Try {
-        Deserialization::Deserialize(buffer, cookieKey);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        return false;
-    }
-
-    Cookie searchPattern;
-    searchPattern.cookieId = cookieKey;
-
-    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
-    if (searchResult != NULL) {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-        Serialization::Serialize(send, searchResult->smackLabel);
-    } else {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
-    }
-
-    return true;
-}
-
-bool CookieService::privilegeByCookieGidRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
-    std::vector<char> cookieKey;
-    int gid;
-
-    Try {
-        Deserialization::Deserialize(buffer, cookieKey);
-        Deserialization::Deserialize(buffer, gid);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        return false;
-    }
-
-    Cookie searchPattern;
-    searchPattern.cookieId = cookieKey;
-
-    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
-    if (searchResult != NULL)
-        //search for specified GID on permissions list
-        for (size_t i = 0; i < searchResult->permissions.size(); i++)
-            if (searchResult->permissions[i] == gid) {
-                Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-                return true;
-            }
-
-    Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_ACCESS_DENIED);
-
-    return true;
-}
-
-bool CookieService::privilegeByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
-    std::vector<char> cookieKey;
-    std::string subject;
-    std::string object;
-    std::string access;
-
-    Try {
-        Deserialization::Deserialize(buffer, cookieKey);
-        Deserialization::Deserialize(buffer, object);
-        Deserialization::Deserialize(buffer, access);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        return false;
-    }
-
-    Cookie searchPattern;
-    searchPattern.cookieId = cookieKey;
-
-    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
-    if (searchResult != NULL) {
-        if (!smack_check()) {
-            Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-        } else {
-            subject = searchResult->smackLabel;
-            int retval;
-
-            if ((retval = smack_have_access(subject.c_str(), object.c_str(), access.c_str())) == 1)
-                Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-            else {
-                Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_ACCESS_DENIED);
-                LogSmackAudit("SS_SMACK: "
-                    << " subject=" << subject
-                    << ", object=" << object
-                    << ", access=" << access
-                    << ", result=" << retval);
-            }
-        }
-    } else {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
-    }
-
-    return true;
-}
-
-bool CookieService::uidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
-    std::vector<char> cookieKey;
-
-    Try {
-        Deserialization::Deserialize(buffer, cookieKey);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        return false;
-    }
-
-    Cookie searchPattern;
-    searchPattern.cookieId = cookieKey;
-
-    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
-    if (searchResult != NULL) {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-        Serialization::Serialize(send, (int)searchResult->uid);
-    } else {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
-    }
-
-    return true;
-}
-
-bool CookieService::gidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send)
-{
-    std::vector<char> cookieKey;
-
-    Try {
-        Deserialization::Deserialize(buffer, cookieKey);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        return false;
-    }
-
-    Cookie searchPattern;
-    searchPattern.cookieId = cookieKey;
-
-    const Cookie *searchResult = m_cookieJar.SearchCookie(searchPattern, CompareType::COOKIE_ID);
-
-    if (searchResult != NULL) {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_SUCCESS);
-        Serialization::Serialize(send, (int)searchResult->gid);
-    } else {
-        Serialization::Serialize(send, (int)SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE);
-    }
-
-    return true;
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/service/cookie.h b/src/server2/service/cookie.h
deleted file mode 100644 (file)
index b899e2f..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        cookie.h
- * @author      Pawel Polawski (p.polawski@partner.samsung.com)
- * @version     1.0
- * @brief       This function contain header for implementation of cookie get API
- */
-
-#ifndef _SECURITY_SERVER_COOKIE_GET_
-#define _SECURITY_SERVER_COOKIE_GET_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-#include <dpl/serialization.h>
-#include <message-buffer.h>
-#include <connection-info.h>
-#include <security-server-common.h>
-#include <cookie-jar.h>
-
-namespace SecurityServer {
-
-class CookieService  :
-    public SecurityServer::GenericSocketService
-  , public SecurityServer::ServiceThread<CookieService>
-{
-public:
-
-    ServiceDescriptionVector GetServiceDescription();
-
-    DECLARE_THREAD_EVENT(AcceptEvent, accept)
-    DECLARE_THREAD_EVENT(WriteEvent, write)
-    DECLARE_THREAD_EVENT(ReadEvent, process)
-    DECLARE_THREAD_EVENT(CloseEvent, close)
-
-    void accept(const AcceptEvent &event);
-    void write(const WriteEvent &event);
-    void process(const ReadEvent &event);
-    void close(const CloseEvent &event);
-
-private:
-    bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
-
-    bool cookieRequest(MessageBuffer &send, int socket);
-
-    bool pidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
-    bool smackLabelByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
-    bool privilegeByCookieGidRequest(MessageBuffer &buffer, MessageBuffer &send);
-    bool privilegeByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
-
-    bool uidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
-    bool gidByCookieRequest(MessageBuffer &buffer, MessageBuffer &send);
-
-    CookieJar m_cookieJar;
-
-    ConnectionInfoMap m_connectionInfoMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_APP_ENABLE_PERMISSIONS_
diff --git a/src/server2/service/data-share.cpp b/src/server2/service/data-share.cpp
deleted file mode 100644 (file)
index 0c64a60..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        data-share.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of api-data-share service.
- */
-
-#include <sys/smack.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <data-share.h>
-#include <security-server.h>
-#include <security-server-util.h>
-#include <smack-check.h>
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector SharedMemoryService::GetServiceDescription() {
-    return ServiceDescriptionVector
-        {{SERVICE_SOCKET_SHARED_MEMORY, "security-server::api-data-share"}};
-}
-
-void SharedMemoryService::accept(const AcceptEvent &event) {
-    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-}
-
-void SharedMemoryService::write(const WriteEvent &event) {
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-bool SharedMemoryService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
-    LogDebug("Iteration begin");
-    static const char * const revoke = "-----";
-    static const char * const permissions = "rwxat";
-    char *providerLabel = NULL;
-    std::string clientLabel;
-    int clientPid = 0;
-    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-    struct smack_accesses *smack = NULL;
-
-    if (!buffer.Ready()) {
-        return false;
-    }
-
-    Try {
-        Deserialization::Deserialize(buffer, clientLabel);
-        Deserialization::Deserialize(buffer, clientPid);
-     } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    if (smack_check()) {
-        if (0 != smack_new_label_from_socket(conn.sock, &providerLabel)) {
-            LogDebug("Error in smack_new_label_from_socket");
-            retCode = SECURITY_SERVER_API_ERROR_BAD_REQUEST;
-            goto end;
-        }
-
-        if (!util_smack_label_is_valid(clientLabel.c_str())) {
-            LogDebug("Invalid smack label: " << clientLabel);
-            retCode = SECURITY_SERVER_API_ERROR_BAD_REQUEST;
-            goto end;
-        }
-
-        if (smack_accesses_new(&smack)) {
-            LogDebug("Error in smack_accesses_new");
-            goto end;
-        }
-
-        if (smack_accesses_add_modify(smack, clientLabel.c_str(), providerLabel,
-              permissions, revoke))
-        {
-            LogDebug("Error in smack_accesses_add_modify");
-            goto end;
-        }
-
-        if (smack_accesses_apply(smack)) {
-            LogDebug("Error in smack_accesses_apply");
-            retCode = SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
-            goto end;
-        }
-        LogDebug("Access granted. Subject: " << clientLabel << " Provider: " << providerLabel);
-    }
-    retCode = SECURITY_SERVER_API_SUCCESS;
-end:
-    free(providerLabel);
-    smack_accesses_free(smack);
-
-    MessageBuffer sendBuffer;
-    Serialization::Serialize(sendBuffer, retCode);
-    m_serviceManager->Write(conn, sendBuffer.Pop());
-    return true;
-}
-
-void SharedMemoryService::process(const ReadEvent &event) {
-    LogDebug("Read event for counter: " << event.connectionID.counter);
-    auto &buffer = m_messageBufferMap[event.connectionID.counter];
-    buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, buffer));
-}
-
-void SharedMemoryService::close(const CloseEvent &event) {
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    m_messageBufferMap.erase(event.connectionID.counter);
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/service/data-share.h b/src/server2/service/data-share.h
deleted file mode 100644 (file)
index 1626c32..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        data-share.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of api-data-share
- */
-
-#ifndef _SECURITY_SERVER_DATA_SHARE_
-#define _SECURITY_SERVER_DATA_SHARE_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <message-buffer.h>
-
-namespace SecurityServer {
-
-class SharedMemoryService
-  : public SecurityServer::GenericSocketService
-  , public SecurityServer::ServiceThread<SharedMemoryService>
-{
-public:
-    typedef std::map<int, MessageBuffer> MessageBufferMap;
-
-    ServiceDescriptionVector GetServiceDescription();
-
-    DECLARE_THREAD_EVENT(AcceptEvent, accept)
-    DECLARE_THREAD_EVENT(WriteEvent, write)
-    DECLARE_THREAD_EVENT(ReadEvent, process)
-    DECLARE_THREAD_EVENT(CloseEvent, close)
-
-    void accept(const AcceptEvent &event);
-    void write(const WriteEvent &event);
-    void process(const ReadEvent &event);
-    void close(const CloseEvent &event);
-private:
-    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
-
-    MessageBufferMap m_messageBufferMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_DATA_SHARE_
diff --git a/src/server2/service/echo.cpp b/src/server2/service/echo.cpp
deleted file mode 100644 (file)
index f4acc64..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        server-main2.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Implementation of sample service.
- */
-
-#include <dpl/log/log.h>
-
-#include <protocols.h>
-#include <echo.h>
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector EchoService::GetServiceDescription() {
-    return ServiceDescriptionVector
-        {{SERVICE_SOCKET_ECHO, "security-server::api-echo"}};
-}
-
-void EchoService::accept(const AcceptEvent &event) {
-    LogDebug("Accept event. ConnectionID: " << event.connectionID.sock
-        << " ServiceID: " << event.interfaceID);
-}
-
-void EchoService::write(const WriteEvent &event) {
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-void EchoService::process(const ReadEvent &event) {
-    LogDebug("ReadEvent. ConnectionID: " << event.connectionID.sock <<
-      " Buffer size: " << event.rawBuffer.size());
-    m_serviceManager->Write(event.connectionID, event.rawBuffer);
-    LogDebug("Write completed");
-}
-
-void EchoService::close(const CloseEvent &event) {
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/service/echo.h b/src/server2/service/echo.h
deleted file mode 100644 (file)
index 80d3685..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        echo.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Sample service implementation.
- */
-
-#ifndef _SECURITY_SERVER_ECHO_
-#define _SECURITY_SERVER_ECHO_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <dpl/serialization.h>
-
-#include <message-buffer.h>
-
-namespace SecurityServer {
-
-class EchoService
-  : public SecurityServer::GenericSocketService
-  , public SecurityServer::ServiceThread<EchoService>
-{
-public:
-    ServiceDescriptionVector GetServiceDescription();
-
-    DECLARE_THREAD_EVENT(AcceptEvent, accept)
-    DECLARE_THREAD_EVENT(WriteEvent, write)
-    DECLARE_THREAD_EVENT(ReadEvent, process)
-    DECLARE_THREAD_EVENT(CloseEvent, close)
-
-    void accept(const AcceptEvent &event);
-    void write(const WriteEvent &event);
-    void process(const ReadEvent &event);
-    void close(const CloseEvent &event);
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_ECHO_
diff --git a/src/server2/service/get-gid.cpp b/src/server2/service/get-gid.cpp
deleted file mode 100644 (file)
index 86ca202..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        get-gid.cpp
- * @author      Jan Olszak (j.olszak@samsung.com)
- * @version     1.0
- * @brief       Implementation of api-get-gid service.
- */
-
-#include <unistd.h>
-#include <sys/smack.h>
-#include <grp.h>
-#include <unistd.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <get-gid.h>
-#include <security-server.h>
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector GetGidService::GetServiceDescription() {
-    return ServiceDescriptionVector
-        {{SERVICE_SOCKET_GET_GID, "*"}};
-}
-
-void GetGidService::accept(const AcceptEvent &event) {
-    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-}
-
-void GetGidService::write(const WriteEvent &event) {
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-
-/*
- * Searches for group ID by given group name
- */
-int GetGidService::setGid(std::string& obj)
-{
-    int ret = 0;
-    struct group *grpbuf = NULL;
-    struct group grp;
-    std::vector<char> buf;
-
-    /*
-     * The maximum needed size for buf can be found using sysconf(3)
-     * with the argument _SC_GETGR_R_SIZE_MAX. If _SC_GETGR_R_SIZE_MAX is not
-     * returned we set max_buf_size to 1024 bytes. Enough to store few groups.
-     */
-    long int maxBufSize = sysconf(_SC_GETGR_R_SIZE_MAX);
-    if (maxBufSize == -1)
-        maxBufSize = 1024;
-
-
-    /*
-     * There can be some corner cases when for example user is assigned to a
-     * lot of groups. In that case if buffer is to small getgrnam_r will
-     * return ERANGE error. Solution could be calling getgrnam_r with bigger
-     * buffer until it's big enough.
-     */
-    do {
-        try{
-            buf.resize(maxBufSize);
-        }catch(std::bad_alloc&) {
-            ret = SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
-            LogError("Out Of Memory");
-            return ret;
-        }
-        maxBufSize *= 2;
-    } while ((ret = getgrnam_r(obj.c_str(), &grp, &(buf[0]), buf.size(), &grpbuf)) == ERANGE);
-
-    // Check for errors:
-    if (ret != 0){
-        ret = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-        LogError("getgrnam_r failed with error: " << strerror(errno));
-        return ret;
-
-    } else if (grpbuf == NULL) {
-        ret = SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT;
-        LogError("Cannot find gid for group: " << obj);
-        return ret;
-    }
-
-    m_gid = grpbuf->gr_gid;
-
-    return ret;
-}
-
-
-bool GetGidService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
-    LogDebug("Iteration begin");
-    std::string objectName;
-    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-    if (!buffer.Ready()) {
-        return false;
-    }
-
-    // Get objects name:
-    Try {
-        Deserialization::Deserialize(buffer, objectName);
-     } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    // Get GID
-    retCode = setGid(objectName);
-
-    // Send the result
-    MessageBuffer sendBuffer;
-    Serialization::Serialize(sendBuffer, retCode);
-    Serialization::Serialize(sendBuffer, m_gid);
-    m_serviceManager->Write(conn, sendBuffer.Pop());
-    return true;
-}
-
-void GetGidService::process(const ReadEvent &event) {
-    LogDebug("Read event for counter: " << event.connectionID.counter);
-    auto &buffer = m_messageBufferMap[event.connectionID.counter];
-    buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, buffer));
-}
-
-void GetGidService::close(const CloseEvent &event) {
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    m_messageBufferMap.erase(event.connectionID.counter);
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/service/get-gid.h b/src/server2/service/get-gid.h
deleted file mode 100644 (file)
index 332191d..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        get-gid.h
- * @author      Jan Olszak (j.olszak@samsung.com)
- * @version     1.0
- * @brief       Implementation of api-get-gid
- */
-
-#ifndef _SECURITY_SERVER_GET_GID_
-#define _SECURITY_SERVER_GET_GID_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <dpl/serialization.h>
-#include <message-buffer.h>
-
-#include <security-server-common.h>
-
-namespace SecurityServer {
-
-class GetGidService  : 
-    public SecurityServer::GenericSocketService
-  , public SecurityServer::ServiceThread<GetGidService>
-{
-public:
-    typedef std::map<int, MessageBuffer> MessageBufferMap;
-
-    ServiceDescriptionVector GetServiceDescription();
-
-    DECLARE_THREAD_EVENT(AcceptEvent, accept)
-    DECLARE_THREAD_EVENT(WriteEvent, write)
-    DECLARE_THREAD_EVENT(ReadEvent, process)
-    DECLARE_THREAD_EVENT(CloseEvent, close)
-
-    void accept(const AcceptEvent &event);
-    void write(const WriteEvent &event);
-    void process(const ReadEvent &event);
-    void close(const CloseEvent &event);
-private:
-    gid_t m_gid;
-    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
-    int  setGid(std::string& objectName);
-    MessageBufferMap m_messageBufferMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_GET_GID_
diff --git a/src/server2/service/get-object-name.cpp b/src/server2/service/get-object-name.cpp
deleted file mode 100644 (file)
index b3491a9..0000000
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        get-object-name.cpp
- * @author      Jan Olszak (j.olszak@samsung.com)
- * @version     1.0
- * @brief       Implementation of api-get-object-name service.
- */
-
-#include <sys/smack.h>
-#include <grp.h>
-#include <unistd.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <get-object-name.h>
-#include <security-server.h>
-
-#include <vector>
-
-namespace SecurityServer {
-
-GetObjectNameService::ServiceDescriptionVector GetObjectNameService::GetServiceDescription() {
-    return ServiceDescriptionVector
-        {{SERVICE_SOCKET_GET_OBJECT_NAME, "*"}};
-}
-
-void GetObjectNameService::accept(const AcceptEvent &event) {
-    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-}
-
-void GetObjectNameService::write(const WriteEvent &event) {
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-
-
-/*
- * Searches for group NAME by given group id
- */
-int GetObjectNameService::setName(const gid_t gid)
-{
-    int ret = 0;
-    struct group *grpbuf = NULL;
-    struct group grp;
-    std::vector<char> buf;
-
-    /*
-     * The maximum needed size for buf can be found using sysconf(3)
-     * with the argument _SC_GETGR_R_SIZE_MAX. If _SC_GETGR_R_SIZE_MAX is not
-     * returned we set max_buf_size to 1024 bytes. Enough to store few groups.
-     */
-    long int maxBufSize = sysconf(_SC_GETGR_R_SIZE_MAX);
-    if (maxBufSize == -1)
-        maxBufSize = 1024;
-
-
-    /*
-     * There can be some corner cases when for example user is assigned to a
-     * lot of groups. In that case if buffer is to small getgrnam_r will
-     * return ERANGE error. Solution could be calling getgrnam_r with bigger
-     * buffer until it's big enough.
-     */
-    do {
-        try{
-            buf.resize(maxBufSize);
-        }catch(std::bad_alloc&) {
-            ret = SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY;
-            LogError("Out Of Memory");
-            return ret;
-        }
-        maxBufSize *= 2;
-
-    } while ((ret = getgrgid_r(gid, &grp, &(buf[0]), buf.size(), &grpbuf)) == ERANGE);
-
-    // Check for errors:
-    if (ret != 0){
-        ret = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-        LogError("getgrgid_r failed with error: " << strerror(errno));
-        return ret;
-
-    } else if (grpbuf == NULL) {
-        ret = SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT;
-        LogError("Cannot find name for group: " << gid);
-        return ret;
-    }
-
-    m_name = grpbuf->gr_name;
-
-    return ret;
-}
-
-
-bool GetObjectNameService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
-    LogDebug("Iteration begin");
-    gid_t gid;
-    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-    if (!buffer.Ready()) {
-        return false;
-    }
-
-    // Get objects GID:
-    Try {
-        Deserialization::Deserialize(buffer, gid);
-     } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    // Get name
-    retCode = setName(gid);
-
-    // Send the result
-    MessageBuffer sendBuffer;
-    Serialization::Serialize(sendBuffer, retCode);
-    Serialization::Serialize(sendBuffer, m_name);
-    m_serviceManager->Write(conn, sendBuffer.Pop());
-    return true;
-}
-
-void GetObjectNameService::process(const ReadEvent &event) {
-    LogDebug("Read event for counter: " << event.connectionID.counter);
-    auto &buffer = m_messageBufferMap[event.connectionID.counter];
-    buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, buffer));
-}
-
-void GetObjectNameService::close(const CloseEvent &event) {
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    m_messageBufferMap.erase(event.connectionID.counter);
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/service/get-object-name.h b/src/server2/service/get-object-name.h
deleted file mode 100644 (file)
index 3a6bd4c..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        get-object-name.h
- * @author      Jan Olszak (j.olszak@samsung.com)
- * @version     1.0
- * @brief       Implementation of api-get-object-name service.
- */
-
-#ifndef _SECURITY_SERVER_SERV_GET_OBJECT_NAME_
-#define _SECURITY_SERVER_SERV_GET_OBJECT_NAME_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <dpl/serialization.h>
-#include <message-buffer.h>
-
-#include <security-server-common.h>
-
-namespace SecurityServer {
-
-class GetObjectNameService  :
-    public SecurityServer::GenericSocketService
-  , public SecurityServer::ServiceThread<GetObjectNameService>
-{
-public:
-    typedef std::map<int, MessageBuffer> MessageBufferMap;
-
-    ServiceDescriptionVector GetServiceDescription();
-
-    DECLARE_THREAD_EVENT(AcceptEvent, accept)
-    DECLARE_THREAD_EVENT(WriteEvent, write)
-    DECLARE_THREAD_EVENT(ReadEvent, process)
-    DECLARE_THREAD_EVENT(CloseEvent, close)
-
-    void accept(const AcceptEvent &event);
-    void write(const WriteEvent &event);
-    void process(const ReadEvent &event);
-    void close(const CloseEvent &event);
-
-private:
-    std::string m_name;
-    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
-    int  setName(gid_t gid);
-    MessageBufferMap m_messageBufferMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_SERV_GET_OBJECT_NAME_
diff --git a/src/server2/service/open-for-manager.cpp b/src/server2/service/open-for-manager.cpp
deleted file mode 100644 (file)
index 63949e4..0000000
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        open-for-manager.cpp
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @version     1.0
- * @brief       Implementation of open-for management functions
- */
-
-#include "open-for-manager.h"
-
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <dirent.h>
-#include <fcntl.h>
-
-#include <sys/smack.h>
-#include <smack-check.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <security-server.h>
-#include <security-server-util.h>
-#include <security-server-comm.h>
-
-const std::string DATA_DIR = "/var/run/security-server";
-const std::string PROHIBITED_STR = "..";
-const std::string ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ \
-                                   abcdefghijklmnopqrstuvwxyz \
-                                   0123456789._-";
-
-namespace SecurityServer
-{
-    // SockCred implementations
-    SockCred::SockCred()
-    {
-        m_len = sizeof(struct ucred);
-        memset(&m_cr, 0, m_len);
-    }
-
-    bool SockCred::getCred(int socket)
-    {
-        if (getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &m_cr, &m_len)) {
-            int err = errno;
-            LogError("Unable to get client credentials: " << strerror(err));
-            return true;
-        }
-
-        if (smack_check()) {
-            char label[SMACK_LABEL_LEN + 1];
-            if (PC_OPERATION_SUCCESS != get_smack_label_from_process(m_cr.pid, label)) {
-                LogError("Unable to get smack label of process.");
-                return true;
-            }
-            m_sockSmackLabel = label;
-        } else
-            m_sockSmackLabel = "";
-
-        return false;
-    }
-
-    std::string SockCred::getLabel() const
-    {
-        return m_sockSmackLabel;
-    }
-
-    // SharedFile implementations
-    SharedFile::SharedFile()
-    {
-        if (!dirExist(DATA_DIR.c_str()))
-            mkdir(DATA_DIR.c_str(), 0700);
-        else {
-            deleteDir(DATA_DIR.c_str());
-            mkdir(DATA_DIR.c_str(), 0700);
-        }
-    }
-
-    bool SharedFile::fileExist(const std::string &filename) const
-    {
-        std::string filepath = DATA_DIR + "/" + filename;
-        struct stat buf;
-
-        return ((lstat(filepath.c_str(), &buf) == 0) &&
-                (((buf.st_mode) & S_IFMT) != S_IFLNK));
-    }
-
-    bool SharedFile::dirExist(const std::string &dirpath) const
-    {
-        struct stat buf;
-
-        return ((lstat(dirpath.c_str(), &buf) == 0) &&
-                (((buf.st_mode) & S_IFMT) == S_IFDIR));
-    }
-
-    bool SharedFile::deleteDir(const std::string &dirpath) const
-    {
-        DIR *dirp;
-        struct dirent *dp;
-        char path[PATH_MAX];
-
-        if ((dirp = opendir(dirpath.c_str())) == NULL) {
-            int err = errno;
-            LogError("Cannot open data directory. " << strerror(err));
-            return true;
-        }
-
-        while ((dp = readdir(dirp)) != NULL) {
-            if (strcmp(dp->d_name, ".") && strcmp(dp->d_name, "..")) {
-                snprintf(path, (size_t) PATH_MAX, "%s/%s", dirpath.c_str(), dp->d_name);
-                if (dp->d_type == DT_DIR) {
-                    deleteDir(path);
-                } else {
-                    unlink(path);
-                }
-            }
-        }
-        closedir(dirp);
-        rmdir(dirpath.c_str());
-
-        return false;
-    }
-
-    bool SharedFile::createFile(const std::string &filename)
-    {
-        int fd = -1;
-        std::string filepath = DATA_DIR + "/" + filename;
-
-        fd = TEMP_FAILURE_RETRY(open(filepath.c_str(), O_CREAT | O_WRONLY | O_EXCL, 0600));
-        int err = errno;
-        if (-1 == fd) {
-            LogError("Cannot create file. Error in open(): " << strerror(err));
-            return true;
-        }
-
-        TEMP_FAILURE_RETRY(close(fd));
-
-        return false;
-    }
-
-    int SharedFile::openFile(const std::string &filename)
-    {
-        int fd = -1;
-        std::string filepath = DATA_DIR + "/" + filename;
-
-        fd = TEMP_FAILURE_RETRY(open(filepath.c_str(), O_CREAT | O_RDWR, 0600));
-        int err = errno;
-        if (-1 == fd) {
-            LogError("Cannot open file. Error in open(): " << strerror(err));
-            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-        }
-
-        return fd;
-    }
-
-    bool SharedFile::setFileLabel(const std::string &filename, const std::string &label) const
-    {
-        std::string filepath = DATA_DIR + "/" + filename;
-
-        if (smack_setlabel(filepath.c_str(), label.c_str(), SMACK_LABEL_ACCESS)) {
-            LogError("Cannot set SMACK label on file.");
-            return true;
-        }
-
-        return false;
-    }
-
-    bool SharedFile::getFileLabel(const std::string &filename)
-    {
-        std::string filepath = DATA_DIR + "/" + filename;
-
-        if (smack_check()) {
-            char *label = NULL;
-            if (PC_OPERATION_SUCCESS != smack_getlabel(filepath.c_str(), &label, SMACK_LABEL_ACCESS)) {
-                LogError("Unable to get smack label of process.");
-                return true;
-            }
-            m_fileSmackLabel = label;
-            free(label);
-        } else
-            m_fileSmackLabel.clear();
-
-        return false;
-    }
-
-    bool SharedFile::checkFileNameSyntax(const std::string &filename) const
-    {
-        std::size_t found = filename.find_first_not_of(ALLOWED_CHARS);
-
-        if (found != std::string::npos || '-' == filename[0] ||
-            '.' == filename[0]) {
-            LogError("Illegal character in filename.");
-            return true;
-        }
-
-        found = filename.find(PROHIBITED_STR);
-        if (found != std::string::npos) {
-            LogError("Illegal string in filename.");
-            return true;
-        }
-
-        return false;
-    }
-
-    int SharedFile::getFD(const std::string &filename, int socket, int &fd)
-    {
-        if (checkFileNameSyntax(filename))
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-        if (m_sockCred.getCred(socket))
-            return SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED;
-
-        if (!fileExist(filename)) {
-            LogSecureDebug("File: " << filename.c_str() << " does not exist.");
-
-            if (createFile(filename))
-                return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-        }
-
-        if (getFileLabel(filename))
-            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-        if (setFileLabel(filename, m_sockCred.getLabel()))
-            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-        fd = openFile(filename);
-
-        if (setFileLabel(filename, m_fileSmackLabel))
-            return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-} //namespace SecurityServer
diff --git a/src/server2/service/open-for-manager.h b/src/server2/service/open-for-manager.h
deleted file mode 100644 (file)
index 83cf0da..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        open-for-manager.h
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @version     1.0
- * @brief       Implementation of open-for management functions
- */
-
-#ifndef _OPEN_FOR_MANAGER_H_
-#define _OPEN_FOR_MANAGER_H_
-
-#include "security-server-common.h"
-
-#include <sys/socket.h>
-#include <sys/types.h>
-
-#include <string>
-
-namespace SecurityServer
-{
-    // classess
-    class SockCred
-    {
-    public:
-        SockCred();
-        bool getCred(int socket);
-        std::string getLabel(void) const;
-
-    private:
-        struct ucred m_cr;
-        unsigned m_len;
-        std::string m_sockSmackLabel;
-    };
-
-    class SharedFile
-    {
-    public:
-        SharedFile();
-        int getFD(const std::string &filename, int socket, int &fd);
-
-    private:
-        bool fileExist(const std::string &filename) const;
-        bool dirExist(const std::string &dirpath) const;
-        bool deleteDir(const std::string &dirpath) const;
-        int openFile(const std::string &filename);
-        bool createFile(const std::string &filename);
-        bool setFileLabel(const std::string &filename, const std::string &label) const;
-        bool getFileLabel(const std::string &filename);
-        bool checkFileNameSyntax(const std::string &filename) const;
-
-        uid_t m_fileUID;
-        gid_t m_fileGID;
-        mode_t m_fileMode;
-        std::string m_fileSmackLabel;
-
-        SockCred m_sockCred;
-    };
-}
-
-#endif // _OPEN_FOR_MANAGER_H_
diff --git a/src/server2/service/open-for.cpp b/src/server2/service/open-for.cpp
deleted file mode 100644 (file)
index 6b60459..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        open-for.cpp
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @version     1.0
- * @brief       Implementation of open-for service
- */
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <open-for.h>
-#include <unistd.h>
-#include <algorithm>
-
-#include <security-server.h>
-#include <security-server-util.h>
-#include <security-server-comm.h>
-
-namespace {
-// Service may open more than one socket.
-// These ID's will be assigned to sockets
-// and will be used only by service.
-// When new connection arrives, AcceptEvent
-// will be generated with proper ID to inform
-// service about input socket.
-//
-// Please note: SocketManaged does not use it and
-// does not check it in any way.
-//
-// If your service require only one socket
-// (uses only one socket labeled with smack)
-// you may ignore this ID (just pass 0)
-const int SERVICE_SOCKET_ID = 0;
-
-} // namespace anonymous
-
-namespace SecurityServer {
-
-OpenForService::OpenForConnInfo::~OpenForConnInfo() {
-    std::for_each(descriptorsVector.begin(),descriptorsVector.end(), ::close);
-}
-
-GenericSocketService::ServiceDescriptionVector OpenForService::GetServiceDescription() {
-    return ServiceDescriptionVector
-        {{SERVICE_SOCKET_OPEN_FOR, "security-server::api-open-for", SERVICE_SOCKET_ID, true}};
-}
-
-void OpenForService::accept(const AcceptEvent &event)
-{
-    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-}
-
-void OpenForService::write(const WriteEvent &event)
-{
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-void OpenForService::process(const ReadEvent &event)
-{
-    LogDebug("Read event for counter: " << event.connectionID.counter);
-    auto &info = m_connectionInfoMap[event.connectionID.counter];
-    info.buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, info.buffer, info.descriptorsVector));
-}
-
-void OpenForService::close(const CloseEvent &event)
-{
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    auto &descVector = m_connectionInfoMap[event.connectionID.counter].descriptorsVector;
-
-    for (auto iter = descVector.begin(); iter != descVector.end(); ++iter)
-        TEMP_FAILURE_RETRY(::close(*iter));
-
-    m_connectionInfoMap.erase(event.connectionID.counter);
-}
-
-bool OpenForService::processOne(const ConnectionID &conn, MessageBuffer &buffer, std::vector<int> &descVector)
-{
-    LogDebug("Iteration begin");
-
-    std::string filename;
-    MessageBuffer sendBuffer;
-
-    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-    int fd = -1;
-
-    if (!buffer.Ready())
-        return false;
-
-    Try {
-        Deserialization::Deserialize(buffer, filename);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogError("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    retCode = m_sharedFile.getFD(filename, conn.sock, fd);
-    if (fd != -1)
-        descVector.push_back(fd);
-    SendMsgData sendMsgData(retCode, fd);
-
-    m_serviceManager->Write(conn, sendMsgData);
-
-    return true;
-}
-
-} // namespace SecurityServer
diff --git a/src/server2/service/open-for.h b/src/server2/service/open-for.h
deleted file mode 100644 (file)
index 6de08d5..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        open-for.h
- * @author      Zigniew Jasinski (z.jasinski@samsung.com)
- * @version     1.0
- * @brief       Implementation of open-for service
- */
-
-#ifndef _SECURITY_SERVER_OPEN_FOR_
-#define _SECURITY_SERVER_OPEN_FOR_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-#include <message-buffer.h>
-
-#include "security-server-common.h"
-#include "open-for-manager.h"
-
-namespace SecurityServer
-{
-    class OpenForService
-      : public SecurityServer::GenericSocketService
-      , public SecurityServer::ServiceThread<OpenForService>
-    {
-    public:
-        //service functions
-        ServiceDescriptionVector GetServiceDescription();
-
-        DECLARE_THREAD_EVENT(AcceptEvent, accept)
-        DECLARE_THREAD_EVENT(WriteEvent, write)
-        DECLARE_THREAD_EVENT(ReadEvent, process)
-        DECLARE_THREAD_EVENT(CloseEvent, close)
-
-        void accept(const AcceptEvent &event);
-        void write(const WriteEvent &event);
-        void process(const ReadEvent &event);
-        void close(const CloseEvent &event);
-
-    private:
-        typedef std::vector<int> DescriptorVector;
-
-        struct OpenForConnInfo {
-            ~OpenForConnInfo();
-
-            DescriptorVector descriptorsVector;
-            MessageBuffer buffer;
-        };
-
-        typedef std::map<int, OpenForConnInfo> OpenForConnInfoMap;
-
-        //internal service functions
-        bool processOne(const ConnectionID &conn, MessageBuffer &buffer, DescriptorVector &descVector);
-
-        OpenForConnInfoMap m_connectionInfoMap;
-        SharedFile m_sharedFile;
-    };
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_OPEN_FOR_
diff --git a/src/server2/service/password-exception.h b/src/server2/service/password-exception.h
deleted file mode 100644 (file)
index 7679ebd..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password-exception.h
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Definition of PasswordException class.
- */
-
-#ifndef _PASSWORD_EXCEPTION_H_
-#define _PASSWORD_EXCEPTION_H_
-
-#include <dpl/exception.h>
-
-namespace SecurityServer
-{
-    class PasswordException
-    {
-    public:
-        DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
-        DECLARE_EXCEPTION_TYPE(Base, OutOfData)
-        DECLARE_EXCEPTION_TYPE(Base, NoData)
-        DECLARE_EXCEPTION_TYPE(Base, FStreamOpenError)
-        DECLARE_EXCEPTION_TYPE(Base, FStreamWriteError)
-        DECLARE_EXCEPTION_TYPE(Base, FStreamReadError)
-        DECLARE_EXCEPTION_TYPE(Base, MemoryError)
-        DECLARE_EXCEPTION_TYPE(Base, NoPasswords)
-        DECLARE_EXCEPTION_TYPE(Base, PasswordNotActive)
-        DECLARE_EXCEPTION_TYPE(Base, MakeDirError)
-        DECLARE_EXCEPTION_TYPE(Base, TimerError)
-    };
-} //namespace SecurityServer
-
-#endif //_PASSWORD_EXCEPTION_H_
diff --git a/src/server2/service/password-file-buffer.cpp b/src/server2/service/password-file-buffer.cpp
deleted file mode 100644 (file)
index eb97897..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password-file-buffer.h
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of PasswordFileBuffer, used for serialization in PasswordFile class
- */
-
-#include <password-file-buffer.h>
-
-#include <fstream>
-#include <iterator>
-
-#include <dpl/log/log.h>
-
-#include <security-server.h>
-#include <password-exception.h>
-
-namespace SecurityServer
-{
-    PasswordFileBuffer::PasswordFileBuffer(): m_bufferReadBytes(0) {}
-
-    void PasswordFileBuffer::Read(size_t num, void *bytes)
-    {
-        if(m_buffer.empty()) {
-            LogError("Buffer doesn't contain any data.");
-            Throw(PasswordException::NoData);
-        }
-
-        if((m_bufferReadBytes + num) > m_buffer.size()) {
-            LogError("Not enough buffer to read " << num << " data.");
-            Throw(PasswordException::OutOfData);
-        }
-
-        void* ret = memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
-
-        if(ret == 0) {
-            LogError("Failed to read " << num << " bytes.");
-            Throw(PasswordException::MemoryError);
-        }
-
-        m_bufferReadBytes += num;
-    }
-
-    void PasswordFileBuffer::Write(size_t num, const void *bytes)
-    {
-        const char* buffer = static_cast<const char*>(bytes);
-        std::copy(buffer, buffer+num, std::back_inserter(m_buffer));
-    }
-
-    void PasswordFileBuffer::Save(const std::string &path)
-    {
-        std::ofstream file(path, std::ofstream::trunc);
-
-        if(!file.good()) {
-            LogError("Error while opening file stream.");
-            Throw(PasswordException::FStreamOpenError);
-        }
-
-        file.write(m_buffer.data(), m_buffer.size());
-        if(!file) {
-            LogError("Failed to write data.");
-            Throw(PasswordException::FStreamWriteError);
-        }
-    }
-
-    void PasswordFileBuffer::Load(const std::string &path)
-    {
-        std::ifstream file(path, std::ifstream::binary);
-
-        if(!file.good()) {
-            LogError("Error while opening file stream.");
-            Throw(PasswordException::FStreamOpenError);
-        }
-
-        //reset read bytes counter
-        m_bufferReadBytes = 0;
-
-        m_buffer.assign(std::istreambuf_iterator<char>(file),
-                        std::istreambuf_iterator<char>());
-
-        if(!file) {
-            LogError("Failed to read data. Failbit: " << file.fail() << ", Badbit: " << file.bad());
-            Throw(PasswordException::FStreamReadError);
-        }
-    }
-
-} //namespace SecurityServer
diff --git a/src/server2/service/password-file-buffer.h b/src/server2/service/password-file-buffer.h
deleted file mode 100644 (file)
index 419f142..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password-file-buffer.h
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of password file buffer, used for serialization in password-manager.h
- */
-
-#ifndef _PASSWORD_FILE_BUFFER_H_
-#define _PASSWORD_FILE_BUFFER_H_
-
-#include <stddef.h>
-#include <vector>
-#include <string>
-
-#include <dpl/serialization.h>
-
-namespace SecurityServer
-{
-    class PasswordFileBuffer: public IStream
-    {
-    public:
-        PasswordFileBuffer();
-
-        virtual void Read(size_t num, void *bytes);
-        virtual void Write(size_t num, const void *bytes);
-
-        void Save(const std::string &path);
-        void Load(const std::string &path);
-
-    private:
-        typedef std::vector<char> DataBuffer;
-
-        DataBuffer m_buffer;
-        size_t m_bufferReadBytes;
-    };
-} //namespace SecurityServer
-
-#endif
diff --git a/src/server2/service/password-file.cpp b/src/server2/service/password-file.cpp
deleted file mode 100644 (file)
index 5f20fc2..0000000
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password-file.cpp
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of PasswordFile, used to manage password files.
- */
-#include <password-file.h>
-
-#include <fstream>
-#include <algorithm>
-
-#include <openssl/sha.h>
-
-#include <sys/stat.h>
-
-#include <dpl/log/log.h>
-
-#include <security-server.h>
-#include <password-exception.h>
-#include <password-file-buffer.h>
-
-const std::string DATA_DIR = "/opt/data/security-server";
-const std::string PASSWORD_FILE = "password.pwd";
-const std::string ATTEMPT_FILE = "attempt";
-const double RETRY_TIMEOUT = 0.5;
-
-namespace SecurityServer
-{
-    PasswordFile::Password::Password()
-    {
-        m_password = PasswordFile::hashPassword("");
-    }
-
-    PasswordFile::Password::Password(const RawHash& password)
-    {
-        m_password = password;
-    }
-
-    PasswordFile::Password::Password(IStream& stream)
-    {
-        Deserialization::Deserialize(stream, m_password);
-    }
-
-    void PasswordFile::Password::Serialize(IStream &stream) const
-    {
-        Serialization::Serialize(stream, m_password);
-    }
-
-    PasswordFile::PasswordFile(): m_maxAttempt(0), m_historySize(0),  m_expireTime(0), m_attempt(0)
-    {
-        // check if data directory exists
-        // if not create it
-        if (!dirExists(DATA_DIR.c_str())) {
-            if(mkdir(DATA_DIR.c_str(), 0700)) {
-                LogError("Failed to create directory for files. Error: " << strerror(errno));
-                Throw(PasswordException::MakeDirError);
-            }
-        }
-
-        preparePwdFile();
-        prepareAttemptFile();
-        resetTimer();
-    }
-
-    void PasswordFile::resetTimer()
-    {
-        m_retryTimerStart = std::chrono::monotonic_clock::now();
-        m_retryTimerStart -= TimeDiff(RETRY_TIMEOUT);
-    }
-
-    void PasswordFile::preparePwdFile()
-    {
-        std::string s_pwdfilePath = DATA_DIR + "/" + PASSWORD_FILE;
-
-        // check if password file exists
-        // if not create it
-        if (!fileExists(s_pwdfilePath)) {
-            LogSecureDebug("PWD_DBG not found password file. Creating.");
-            __mode_t oldMask = umask(S_IRUSR | S_IWUSR);
-
-            //create file
-            writeMemoryToFile();
-
-            umask(oldMask);
-        } else {     //if file exists, load data
-            LogSecureDebug("PWD_DBG found password file. Opening.");
-            loadMemoryFromFile();
-        }
-    }
-
-    void PasswordFile::prepareAttemptFile()
-    {
-        std::string s_attemptfilePath = DATA_DIR + "/" + ATTEMPT_FILE;
-
-        // check if attempt file exists
-        // if not create it
-        if (!fileExists(s_attemptfilePath)) {
-            LogSecureDebug("PWD_DBG not found attempt file. Creating.");
-            __mode_t oldMask = umask(S_IRUSR | S_IWUSR);
-
-            writeAttemptToFile();
-
-            umask(oldMask);
-        } else {
-            LogSecureDebug("PWD_DBG found attempt file. Opening.");
-            std::ifstream attemptFile(s_attemptfilePath);
-            if(!attemptFile.good()) {
-                LogError("Failed to open attempt file.");
-                Throw(PasswordException::FStreamOpenError);
-            }
-
-            attemptFile.read(reinterpret_cast<char*>(&m_attempt), sizeof(unsigned int));
-            if(!attemptFile) {
-                LogError("Failed to read attempt count.");
-                Throw(PasswordException::FStreamReadError);
-            }
-        }
-    }
-
-    bool PasswordFile::fileExists(const std::string &filename) const
-    {
-        struct stat buf;
-
-        return ((stat(filename.c_str(), &buf) == 0));
-    }
-
-    bool PasswordFile::dirExists(const std::string &dirpath) const
-    {
-        struct stat buf;
-
-        return ((stat(dirpath.c_str(), &buf) == 0) && (((buf.st_mode) & S_IFMT) == S_IFDIR));
-    }
-
-    void PasswordFile::writeMemoryToFile() const
-    {
-        PasswordFileBuffer pwdBuffer;
-
-        //serialize password attributes
-        Serialization::Serialize(pwdBuffer, m_maxAttempt);
-        Serialization::Serialize(pwdBuffer, m_historySize);
-        Serialization::Serialize(pwdBuffer, m_expireTime);
-        Serialization::Serialize(pwdBuffer, m_passwords);
-
-        pwdBuffer.Save(DATA_DIR + "/" + PASSWORD_FILE);
-    }
-
-    void PasswordFile::loadMemoryFromFile()
-    {
-        PasswordFileBuffer pwdFile;
-
-        pwdFile.Load(DATA_DIR + "/" + PASSWORD_FILE);
-
-        m_passwords.clear();
-
-        Deserialization::Deserialize(pwdFile, m_maxAttempt);
-        Deserialization::Deserialize(pwdFile, m_historySize);
-        Deserialization::Deserialize(pwdFile, m_expireTime);
-        Deserialization::Deserialize(pwdFile, m_passwords);
-    }
-
-    void PasswordFile::writeAttemptToFile() const
-    {
-        std::ofstream attemptFile(DATA_DIR + "/" + ATTEMPT_FILE, std::ofstream::trunc);
-
-        if(!attemptFile.good()) {
-            LogError("Failed to open attempt file.");
-            Throw(PasswordException::FStreamOpenError);
-        }
-
-        attemptFile.write(reinterpret_cast<const char*>(&m_attempt), sizeof(unsigned int));
-        if(!attemptFile) {
-            LogError("Failed to write attempt count.");
-            Throw(PasswordException::FStreamWriteError);
-        }
-    }
-
-    bool PasswordFile::isPasswordActive() const
-    {
-        return !(m_passwords.empty());
-    }
-
-    void PasswordFile::setHistory(unsigned int history)
-    {
-        //setting history should be independent from password being set
-        m_historySize = history;
-
-        //we want to keep 1 current pwd, plus history amount of passwords.
-        if(m_passwords.size() > 1+history)
-            m_passwords.resize(1+history);
-    }
-
-    unsigned int PasswordFile::getHistorySize() const
-    {
-        return m_historySize;
-    }
-
-    unsigned int PasswordFile::getAttempt() const
-    {
-        return m_attempt;
-    }
-
-    void PasswordFile::resetAttempt()
-    {
-        m_attempt = 0;
-    }
-
-    void PasswordFile::incrementAttempt()
-    {
-        m_attempt++;
-    }
-
-    int PasswordFile::getMaxAttempt() const
-    {
-        return m_maxAttempt;
-    }
-
-    void PasswordFile::setMaxAttempt(unsigned int maxAttempt)
-    {
-        m_maxAttempt = maxAttempt;
-    }
-
-    bool PasswordFile::isPasswordReused(const std::string &password) const
-    {
-        RawHash hashedPwd = hashPassword(password);
-
-        LogSecureDebug("PwdCount: " << m_passwords.size() << ", PwdMaxHistory: " << getHistorySize());
-
-        if(std::find_if(m_passwords.begin(), m_passwords.end(),
-                        [&hashedPwd](const Password& pwd) { return (pwd.m_password == hashedPwd); })
-                != m_passwords.end()) {
-            LogSecureDebug("Passwords match!");
-            return true;
-        }
-
-        LogSecureDebug("isPasswordReused: No passwords match, password not reused.");
-        return false;
-    }
-
-    void PasswordFile::setPassword(const std::string &password)
-    {
-        RawHash hashedPwd = hashPassword(password);
-
-        m_passwords.push_front(Password(hashedPwd));
-
-        //one current password, plus history amount of passwords
-        if(m_passwords.size() > 1+getHistorySize())
-            m_passwords.pop_back();
-    }
-
-    bool PasswordFile::checkPassword(const std::string &password) const
-    {
-        RawHash hashedPwd = hashPassword(password);
-
-        return (hashedPwd == m_passwords.begin()->m_password);
-    }
-
-    void PasswordFile::setExpireTime(int expireTime)
-    {
-        if(isPasswordActive())
-            m_expireTime = expireTime;
-        else {
-            LogError("Can't set expiration time, password not active.");
-            Throw(PasswordException::PasswordNotActive);
-        }
-    }
-
-    time_t PasswordFile::getExpireTime() const
-    {
-        return m_expireTime;
-    }
-
-    time_t PasswordFile::getExpireTimeLeft() const
-    {
-        if(m_expireTime > 0)
-            return (m_expireTime - time(NULL));
-        else
-            return m_expireTime;
-    }
-
-    bool PasswordFile::checkExpiration() const
-    {
-        //return true if expired, else false
-        return ((m_expireTime != 0) && (time(NULL) > m_expireTime));
-    }
-
-    bool PasswordFile::isIgnorePeriod() const
-    {
-        TimePoint retryTimerStop = std::chrono::monotonic_clock::now();
-        TimeDiff diff = retryTimerStop - m_retryTimerStart;
-
-        m_retryTimerStart = retryTimerStop;
-
-        return (diff.count() < RETRY_TIMEOUT);
-    }
-
-    //hashPassword is also used in Password struct constructor, that's why it's static. Moreover
-    //it is assumed that incorrect input password was checked earlier.
-    PasswordFile::RawHash PasswordFile::hashPassword(const std::string &password)
-    {
-        RawHash result(SHA256_DIGEST_LENGTH);
-
-        SHA256_CTX context;
-        SHA256_Init(&context);
-        SHA256_Update(&context, reinterpret_cast<const unsigned char*>(password.c_str()),
-                      password.size());
-        SHA256_Final(result.data(), &context);
-
-        return result;
-    }
-} //namespace SecurityServer
-
diff --git a/src/server2/service/password-file.h b/src/server2/service/password-file.h
deleted file mode 100644 (file)
index 216b9ab..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password-file.h
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of PasswordFile, used to manage password files.
- */
-#ifndef _PASSWORD_FILE_H_
-#define _PASSWORD_FILE_H_
-
-#include <string>
-#include <vector>
-#include <list>
-#include <chrono>
-
-#include <time.h>
-
-#include <dpl/serialization.h>
-
-namespace SecurityServer
-{
-    class PasswordFile
-    {
-    public:
-        PasswordFile();
-
-        void writeMemoryToFile() const;
-        void writeAttemptToFile() const;
-
-        void setPassword(const std::string &password);
-        bool checkPassword(const std::string &password) const;
-        bool isPasswordActive() const;
-
-        void setHistory(unsigned int history);
-        unsigned int getHistorySize() const;
-
-        time_t getExpireTime() const;
-        time_t getExpireTimeLeft() const;
-        void setExpireTime(int expireTime);
-
-        //attempt manipulating functions
-        unsigned int getAttempt() const;
-        void resetAttempt();
-        void incrementAttempt();
-        int getMaxAttempt() const;
-        void setMaxAttempt(unsigned int maxAttempt);
-
-        bool isPasswordReused(const std::string &password) const;
-
-        bool checkExpiration() const;
-        bool isIgnorePeriod() const;
-
-    private:
-        typedef std::vector<unsigned char> RawHash;
-        typedef std::chrono::duration<double> TimeDiff;
-        typedef std::chrono::time_point<std::chrono::monotonic_clock, TimeDiff> TimePoint;
-
-        struct Password: public ISerializable
-        {
-            Password();
-            Password(const RawHash& password);
-            Password(IStream& stream);
-
-            virtual void Serialize(IStream &stream) const;
-
-            RawHash m_password;
-        };
-
-        typedef std::list<Password> PasswordList;
-
-        void loadMemoryFromFile();
-
-        void resetTimer();
-        void preparePwdFile();
-        void prepareAttemptFile();
-        bool fileExists(const std::string &filename) const;
-        bool dirExists(const std::string &dirpath) const;
-        static RawHash hashPassword(const std::string &password);
-
-        mutable TimePoint m_retryTimerStart;
-
-        //password file data
-        PasswordList m_passwords;
-        unsigned int m_maxAttempt;
-        unsigned int m_historySize;
-        time_t m_expireTime;
-
-        //attempt file data
-        unsigned int m_attempt;
-    };
-}    //namespace SecurityServer
-
-#endif
diff --git a/src/server2/service/password-manager.cpp b/src/server2/service/password-manager.cpp
deleted file mode 100644 (file)
index 703caed..0000000
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password-manager.cpp
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of password management functions
- */
-
-#include <password-manager.h>
-
-#include <iostream>
-#include <iterator>
-#include <algorithm>
-
-#include <limits.h>
-
-#include <dpl/log/log.h>
-
-#include <security-server.h>
-#include <protocols.h>
-
-namespace {
-    bool calculateExpiredTime(unsigned int receivedDays, unsigned int &validSecs)
-    {
-        validSecs = 0;
-
-        if(receivedDays == 0)
-            return true;
-
-        time_t curTime = time(NULL);
-
-        if (receivedDays > ((UINT_MAX - curTime) / 86400)) {
-            LogError("Incorrect input param.");
-            return false;
-        } else {
-            validSecs = (curTime + (receivedDays * 86400));
-            return true;
-        }
-
-        //when receivedDays equal to zero, it means infinite password valid time
-        //if receivedDays is 0 return true, else return false (that is, an error)
-        return false;
-    }
-} //namespace
-
-namespace SecurityServer
-{
-    int PasswordManager::isPwdValid(unsigned int &currentAttempt, unsigned int &maxAttempt,
-                                    unsigned int &expirationTime) const
-    {
-        if (m_pwdFile.isIgnorePeriod()) {
-            LogError("Retry timeout occured.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
-        }
-
-        if (!m_pwdFile.isPasswordActive()) {
-            LogError("Current password not active.");
-            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
-        } else {
-            currentAttempt = m_pwdFile.getAttempt();
-            maxAttempt = m_pwdFile.getMaxAttempt();
-            expirationTime = m_pwdFile.getExpireTimeLeft();
-
-            return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
-        }
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    int PasswordManager::checkPassword(const std::string &challenge, unsigned int &currentAttempt,
-                                       unsigned int &maxAttempt, unsigned int &expirationTime)
-    {
-        LogSecureDebug("Inside checkPassword function.");
-
-        if (m_pwdFile.isIgnorePeriod()) {
-            LogError("Retry timeout occurred.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
-        }
-
-        if (!m_pwdFile.isPasswordActive()) {
-            LogError("Password not active.");
-            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
-        }
-
-        currentAttempt = m_pwdFile.getAttempt();
-        maxAttempt = m_pwdFile.getMaxAttempt();
-        expirationTime = m_pwdFile.getExpireTimeLeft();
-
-        if ((maxAttempt != 0) && (currentAttempt >= maxAttempt)) {
-            LogError("Too many tries.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
-        }
-
-        m_pwdFile.incrementAttempt();
-        m_pwdFile.writeAttemptToFile();
-
-        if (!m_pwdFile.checkPassword(challenge)) {
-            LogError("Wrong password.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
-        }
-
-        if (m_pwdFile.checkExpiration()) {
-            LogError("Password expired.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
-        }
-
-        m_pwdFile.resetAttempt();
-        m_pwdFile.writeAttemptToFile();
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    int PasswordManager::setPassword(const std::string &currentPassword,
-                                     const std::string &newPassword,
-                                     const unsigned int receivedAttempts,
-                                     const unsigned int receivedDays)
-    {
-        LogSecureDebug("Curpwd = " << currentPassword << ", newpwd = " << newPassword <<
-                       ", recatt = " << receivedAttempts << ", recdays = " << receivedDays);
-
-        unsigned int valid_secs = 0;
-
-        //check retry timer
-        if (m_pwdFile.isIgnorePeriod()) {
-            LogError("Retry timeout occured.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
-        }
-
-        //check if passwords are correct
-        if (currentPassword.size() > MAX_PASSWORD_LEN) {
-            LogError("Current password length failed.");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        if (newPassword.size() > MAX_PASSWORD_LEN) {
-            LogError("New password length failed.");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        //check delivered currentPassword
-        //when m_passwordActive flag is true, currentPassword shouldn't be empty
-        if (currentPassword.empty() && m_pwdFile.isPasswordActive()) {
-            LogError("Password is already set.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_EXIST;
-        }
-
-        // check attempt
-        unsigned int maxAttempt = m_pwdFile.getMaxAttempt();
-        if ((maxAttempt != 0) && (m_pwdFile.getAttempt() >= maxAttempt)) {
-            LogError("Too many attempts.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
-        }
-
-        //if we didn't exceed max attempts, increment attempt count and save it to separate file
-        m_pwdFile.incrementAttempt();
-        m_pwdFile.writeAttemptToFile();
-
-        //check current password, however only when we don't send empty string as current.
-        if(!currentPassword.empty()) {
-            if(!m_pwdFile.checkPassword(currentPassword)) {
-                LogError("Wrong password.");
-                return SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH;
-            }
-        }
-
-        //check if password expired
-        if (m_pwdFile.checkExpiration()) {
-            LogError("Password expired.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED;
-        }
-
-        //check history
-        if (m_pwdFile.isPasswordActive()) {
-            if (m_pwdFile.isPasswordReused(newPassword)) {
-                LogError("Password reused.");
-                return SECURITY_SERVER_API_ERROR_PASSWORD_REUSED;
-            }
-        }
-
-        if(!calculateExpiredTime(receivedDays, valid_secs)) {
-            LogError("Received expiration time incorrect.");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        //setting password
-        m_pwdFile.setPassword(newPassword);
-        m_pwdFile.setMaxAttempt(receivedAttempts);
-        m_pwdFile.setExpireTime(valid_secs);
-        m_pwdFile.writeMemoryToFile();
-
-        m_pwdFile.resetAttempt();
-        m_pwdFile.writeAttemptToFile();
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    int PasswordManager::setPasswordValidity(const unsigned int receivedDays)
-    {
-        unsigned int valid_secs = 0;
-
-        LogSecureDebug("received_days: " << receivedDays);
-
-        if (!m_pwdFile.isPasswordActive()) {
-            LogError("Current password is not active.");
-            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
-        }
-
-        if(!calculateExpiredTime(receivedDays, valid_secs))
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-        m_pwdFile.setExpireTime(valid_secs);
-        m_pwdFile.writeMemoryToFile();
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    int PasswordManager::resetPassword(const std::string &newPassword,
-                                       const unsigned int receivedAttempts,
-                                       const unsigned int receivedDays)
-    {
-        unsigned int valid_secs = 0;
-
-        if (m_pwdFile.isIgnorePeriod()) {
-            LogError("Retry timeout occured.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
-        }
-
-        if(!calculateExpiredTime(receivedDays, valid_secs))
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-
-        m_pwdFile.setPassword(newPassword);
-        m_pwdFile.setMaxAttempt(receivedAttempts);
-        m_pwdFile.setExpireTime(valid_secs);
-        m_pwdFile.writeMemoryToFile();
-
-        m_pwdFile.resetAttempt();
-        m_pwdFile.writeAttemptToFile();
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    int PasswordManager::setPasswordHistory(const unsigned int history)
-    {
-        if(history > MAX_PASSWORD_HISTORY) {
-            LogError("Incorrect input param.");
-            return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
-        }
-
-        // check retry time
-        if (m_pwdFile.isIgnorePeriod()) {
-            LogError("Retry timeout occurred.");
-            return SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER;
-        }
-
-        m_pwdFile.setHistory(history);
-        m_pwdFile.writeMemoryToFile();
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-
-    int PasswordManager::setPasswordMaxChallenge(const unsigned int maxChallenge)
-    {
-        // check if there is password
-        if (!m_pwdFile.isPasswordActive()) {
-            LogError("Password not active.");
-            return SECURITY_SERVER_API_ERROR_NO_PASSWORD;
-        }
-
-        m_pwdFile.setMaxAttempt(maxChallenge);
-        m_pwdFile.writeMemoryToFile();
-
-        m_pwdFile.resetAttempt();
-        m_pwdFile.writeAttemptToFile();
-
-        return SECURITY_SERVER_API_SUCCESS;
-    }
-} //namespace SecurityServer
diff --git a/src/server2/service/password-manager.h b/src/server2/service/password-manager.h
deleted file mode 100644 (file)
index bef6521..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password-manager.h
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of password management functions
- */
-
-#ifndef _PASSWORDMANAGER_H_
-#define _PASSWORDMANAGER_H_
-
-#include <string>
-
-#include <password-file.h>
-
-namespace SecurityServer
-{
-    class PasswordManager
-    {
-    public:
-        //checking functions
-        int isPwdValid(unsigned int &currentAttempt, unsigned int &maxAttempt,
-                       unsigned int &expirationTime) const;
-        int checkPassword(const std::string& challenge, unsigned int &currentAttempt,
-                          unsigned int &maxAttempt, unsigned int &expTime);
-        //no const in checkPassword, attempts are updated
-
-        //setting functions
-        int setPassword(const std::string &currentPassword, const std::string &newPassword,
-                        const unsigned int receivedAttempts, const unsigned int receivedDays);
-        int setPasswordValidity(const unsigned int receivedDays);
-        int resetPassword(const std::string &newPassword, const unsigned int receivedAttempts,
-                          const unsigned int receivedDays);
-        int setPasswordHistory(const unsigned int history);
-        int setPasswordMaxChallenge(const unsigned int maxChallenge);
-
-    private:
-        PasswordFile m_pwdFile;
-    };
-} //namespace SecurityServer
-
-#endif
diff --git a/src/server2/service/password.cpp b/src/server2/service/password.cpp
deleted file mode 100644 (file)
index d0d4307..0000000
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password.cpp
- * @author      Zbigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of password service
- */
-
-#include <iostream>
-#include <string>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <password.h>
-
-#include <security-server.h>
-#include <password-exception.h>
-
-namespace SecurityServer {
-
-namespace {
-// Service may open more than one socket.
-// These ID's will be assigned to sockets
-// and will be used only by service.
-// When new connection arrives, AcceptEvent
-// will be generated with proper ID to inform
-// service about input socket.
-//
-// Please note: SocketManager does not use it and
-// does not check it in any way.
-//
-// If your service requires only one socket
-// (uses only one socket labeled with smack)
-// you may ignore this ID (just pass 0)
-const InterfaceID SOCKET_ID_CHECK   = 0;
-const InterfaceID SOCKET_ID_SET     = 1;
-
-} // namespace anonymous
-
-GenericSocketService::ServiceDescriptionVector PasswordService::GetServiceDescription()
-{
-    return ServiceDescriptionVector {
-        {SERVICE_SOCKET_PASSWD_CHECK, "security-server::api-password-check", SOCKET_ID_CHECK},
-        {SERVICE_SOCKET_PASSWD_SET,   "security-server::api-password-set",   SOCKET_ID_SET}
-    };
-}
-
-void PasswordService::accept(const AcceptEvent &event)
-{
-    LogSecureDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-
-    auto &info = m_connectionInfoMap[event.connectionID.counter];
-    info.interfaceID = event.interfaceID;
-}
-
-void PasswordService::write(const WriteEvent &event)
-{
-    LogSecureDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-void PasswordService::process(const ReadEvent &event)
-{
-    LogSecureDebug("Read event for counter: " << event.connectionID.counter);
-    auto &info = m_connectionInfoMap[event.connectionID.counter];
-    info.buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, info.buffer, info.interfaceID));
-}
-
-void PasswordService::close(const CloseEvent &event)
-{
-    LogSecureDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    m_connectionInfoMap.erase(event.connectionID.counter);
-}
-
-int PasswordService::processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer,
-                                            unsigned int &cur_att, unsigned int &max_att,
-                                            unsigned int &exp_time)
-{
-    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-    switch (hdr) {
-        case PasswordHdrs::HDR_IS_PWD_VALID:
-            result = m_pwdManager.isPwdValid(cur_att, max_att, exp_time);
-            break;
-
-        case PasswordHdrs::HDR_CHK_PWD: {
-            std::string challenge;
-            Deserialization::Deserialize(buffer, challenge);
-            result = m_pwdManager.checkPassword(challenge, cur_att, max_att, exp_time);
-            break;
-        }
-
-        default:
-            LogError("Unknown msg header.");
-            Throw(Exception::IncorrectHeader);
-    }
-
-    return result;
-}
-
-int PasswordService::processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer)
-{
-    int result = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-    std::string curPwd, newPwd;
-    unsigned int rec_att = 0, rec_days = 0, rec_max_challenge = 0, rec_history = 0;
-
-    switch(hdr) {
-        case PasswordHdrs::HDR_SET_PWD:
-            Deserialization::Deserialize(buffer, curPwd);
-            Deserialization::Deserialize(buffer, newPwd);
-            Deserialization::Deserialize(buffer, rec_att);
-            Deserialization::Deserialize(buffer, rec_days);
-            result = m_pwdManager.setPassword(curPwd, newPwd, rec_att, rec_days);
-            break;
-
-        case PasswordHdrs::HDR_SET_PWD_VALIDITY:
-            Deserialization::Deserialize(buffer, rec_days);
-            result = m_pwdManager.setPasswordValidity(rec_days);
-            break;
-
-        case PasswordHdrs::HDR_SET_PWD_MAX_CHALLENGE:
-            Deserialization::Deserialize(buffer, rec_max_challenge);
-            result = m_pwdManager.setPasswordMaxChallenge(rec_max_challenge);
-            break;
-
-        case PasswordHdrs::HDR_RST_PWD:
-            Deserialization::Deserialize(buffer, newPwd);
-            Deserialization::Deserialize(buffer, rec_att);
-            Deserialization::Deserialize(buffer, rec_days);
-            result = m_pwdManager.resetPassword(newPwd, rec_att, rec_days);
-            break;
-
-        case PasswordHdrs::HDR_SET_PWD_HISTORY:
-            Deserialization::Deserialize(buffer, rec_history);
-            result = m_pwdManager.setPasswordHistory(rec_history);
-            break;
-
-        default:
-            LogError("Unknown msg header.");
-            Throw(Exception::IncorrectHeader);
-    }
-
-    return result;
-}
-
-bool PasswordService::processOne(const ConnectionID &conn, MessageBuffer &buffer,
-                                 InterfaceID interfaceID)
-{
-    LogSecureDebug("Iteration begin");
-
-    MessageBuffer sendBuffer;
-
-    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-    unsigned int cur_att = 0, max_att = 0, exp_time = 0;
-
-    if (!buffer.Ready())
-        return false;
-
-    Try {       //try..catch for MessageBuffer errors, closes connection when exception is thrown
-        int tempHdr;
-        Deserialization::Deserialize(buffer, tempHdr);
-        PasswordHdrs hdr = static_cast<PasswordHdrs>(tempHdr);
-
-        try {   //try..catch for internal service errors, assigns error code for returning.
-            switch (interfaceID) {
-                case SOCKET_ID_CHECK:
-                    retCode = processCheckFunctions(hdr, buffer, cur_att, max_att, exp_time);
-                    break;
-
-                case SOCKET_ID_SET:
-                    retCode = processSetFunctions(hdr, buffer);
-                    break;
-
-                default:
-                    LogError("Wrong interfaceID.");
-                    Throw(Exception::IncorrectHeader);
-            }
-        } catch (PasswordException::Base &e) {
-            LogError("Password error: " << e.DumpToString());
-            retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-        } catch (std::exception &e) {
-            LogError("STD error: " << e.what());
-            retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-        }
-
-        //everything is OK, send return code and extra data
-        Serialization::Serialize(sendBuffer, retCode);
-
-        //Returning additional information should occur only when checking functions
-        //are called, and under certain return values
-        if(interfaceID == SOCKET_ID_CHECK)
-        {
-            switch(retCode)
-            {
-            case SECURITY_SERVER_API_ERROR_PASSWORD_EXIST:
-            case SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH:
-            case SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
-            case SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED:
-                Serialization::Serialize(sendBuffer, cur_att);
-                Serialization::Serialize(sendBuffer, max_att);
-                Serialization::Serialize(sendBuffer, exp_time);
-                break;
-
-            case SECURITY_SERVER_API_SUCCESS:
-                if(hdr == PasswordHdrs::HDR_CHK_PWD) {
-                    Serialization::Serialize(sendBuffer, cur_att);
-                    Serialization::Serialize(sendBuffer, max_att);
-                    Serialization::Serialize(sendBuffer, exp_time);
-                }
-                break;
-
-            default:
-                break;
-            }
-        }
-
-        m_serviceManager->Write(conn, sendBuffer.Pop());
-    } Catch (MessageBuffer::Exception::Base) {
-        LogError("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    } Catch (PasswordService::Exception::Base) {
-        LogError("Incorrect message header. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-
-
-    return true;
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/service/password.h b/src/server2/service/password.h
deleted file mode 100644 (file)
index 0989d81..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        password.h
- * @author      Zigniew Jasinski (z.jasinski@samsung.com)
- * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
- * @version     1.0
- * @brief       Implementation of password service
- */
-
-#ifndef _SECURITY_SERVER_PASSWORD_
-#define _SECURITY_SERVER_PASSWORD_
-
-#include <map>
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-#include <message-buffer.h>
-#include <connection-info.h>
-#include <protocols.h>
-
-#include <password-manager.h>
-
-namespace SecurityServer
-{
-    class PasswordService
-      : public SecurityServer::GenericSocketService
-      , public SecurityServer::ServiceThread<PasswordService>
-    {
-    public:
-        class Exception
-        {
-        public:
-            DECLARE_EXCEPTION_TYPE(SecurityServer::Exception, Base)
-            DECLARE_EXCEPTION_TYPE(Base, IncorrectHeader)
-        };
-
-        //service functions
-        ServiceDescriptionVector GetServiceDescription();
-
-        DECLARE_THREAD_EVENT(AcceptEvent, accept)
-        DECLARE_THREAD_EVENT(WriteEvent, write)
-        DECLARE_THREAD_EVENT(ReadEvent, process)
-        DECLARE_THREAD_EVENT(CloseEvent, close)
-
-        void accept(const AcceptEvent &event);
-        void write(const WriteEvent &event);
-        void process(const ReadEvent &event);
-        void close(const CloseEvent &event);
-
-    private:
-        //internal service functions
-        bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
-        int processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer, unsigned int &cur_att,
-                                   unsigned int &max_att, unsigned int &exp_time);
-        int processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer);
-
-        // service attributes
-        PasswordManager m_pwdManager;
-        ConnectionInfoMap m_connectionInfoMap;
-    };
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_PASSWORD_
diff --git a/src/server2/service/privilege-by-pid.cpp b/src/server2/service/privilege-by-pid.cpp
deleted file mode 100644 (file)
index a5fd4af..0000000
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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        privilege-by-pid.cpp
- * @author      Jan Cybulski (j.cybulski@samsung.com)
- * @version     1.0
- * @brief       Implementation of check-privilege-by-pid service.
- */
-
-#include <sys/smack.h>
-
-#include <dpl/log/log.h>
-#include <dpl/serialization.h>
-
-#include <protocols.h>
-#include <privilege-by-pid.h>
-
-#include <security-server.h>
-#include <security-server-util.h>
-#include <smack-check.h>
-
-#include <privilege-control.h>
-
-namespace SecurityServer {
-
-GenericSocketService::ServiceDescriptionVector PrivilegeByPidService::GetServiceDescription() {
-    //TODO: after enabled smack protection for api use "security-server::api-privilege-by-pid"
-    return ServiceDescriptionVector
-        {{SERVICE_SOCKET_PRIVILEGE_BY_PID, "*" }};
-}
-
-void PrivilegeByPidService::accept(const AcceptEvent &event) {
-    LogDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
-        << " ConnectionID.counter: " << event.connectionID.counter
-        << " ServiceID: " << event.interfaceID);
-}
-
-void PrivilegeByPidService::write(const WriteEvent &event) {
-    LogDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
-        " Size: " << event.size << " Left: " << event.left);
-    if (event.left == 0)
-        m_serviceManager->Close(event.connectionID);
-}
-
-bool PrivilegeByPidService::processOne(const ConnectionID &conn, MessageBuffer &buffer) {
-    LogDebug("Iteration begin");
-
-    int retval;
-    int pid;
-    std::string object;
-    std::string access_rights;
-    char subject[SMACK_LABEL_LEN + 1] = {0};
-
-    int retCode = SECURITY_SERVER_API_ERROR_SERVER_ERROR;
-
-
-    if (!buffer.Ready()) {
-        return false;
-    }
-
-    Try {
-        Deserialization::Deserialize(buffer, pid);
-        Deserialization::Deserialize(buffer, object);
-        Deserialization::Deserialize(buffer, access_rights);
-    } Catch (MessageBuffer::Exception::Base) {
-        LogDebug("Broken protocol. Closing socket.");
-        m_serviceManager->Close(conn);
-        return false;
-    }
-
-    if (smack_check()) {
-        retval = smack_pid_have_access(pid, object.c_str(), access_rights.c_str());
-        LogDebug("smack_pid_have_access returned " << retval);
-
-        if (get_smack_label_from_process(pid, subject) != PC_OPERATION_SUCCESS) {
-            // subject label is set to empty string
-            LogError("get_smack_label_from_process failed. Subject label has not been read.");
-        } else {
-            SECURE_SLOGD("Subject label of client PID %d is: %s", pid, subject);
-        }
-    } else {
-        LogDebug("SMACK is not available. Subject label has not been read.");
-        retval = 1;
-    }
-//    char *path = read_exe_path_from_proc(pid);
-//
-//    if (retval > 0)
-//        LogDebug("SS_SMACK: "
-//                << "caller_pid=" << pid
-//                << ", subject=" << subject
-//                << ", object=" << object
-//                << ", access=" << access_rights
-//                << ", result=" << retval
-//                << ", caller_path=" << path);
-//    else
-//        LogError("SS_SMACK: "
-//                << "caller_pid=" << pid
-//                << ", subject=" << subject
-//                << ", object=" << object
-//                << ", access=" << access_rights
-//                << ", result=" << retval
-//                << ", caller_path=" << path);
-//
-//    if (path != NULL)
-//        free(path);
-
-
-    if (retval == 1)   //there is permission
-        retCode = SECURITY_SERVER_API_SUCCESS;
-    else                //there is no permission
-        retCode = SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
-
-    MessageBuffer sendBuffer;
-    Serialization::Serialize(sendBuffer, retCode);
-    m_serviceManager->Write(conn, sendBuffer.Pop());
-
-    if (retval != 1) {
-        char *path = read_exe_path_from_proc(pid);
-
-        LogSmackAudit("SS_SMACK: "
-            << "caller_pid=" << pid
-            << ", subject="  << subject
-            << ", object="   << object
-            << ", access="   << access_rights
-            << ", result="   << retval
-            << ", caller_path=" << (path ? path : ""));
-
-        free(path);
-    }
-
-    return true;
-}
-
-void PrivilegeByPidService::process(const ReadEvent &event) {
-    LogDebug("Read event for counter: " << event.connectionID.counter);
-    auto &buffer = m_messageBufferMap[event.connectionID.counter];
-    buffer.Push(event.rawBuffer);
-
-    // We can get several requests in one package.
-    // Extract and process them all
-    while(processOne(event.connectionID, buffer));
-}
-
-void PrivilegeByPidService::close(const CloseEvent &event) {
-    LogDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
-    m_messageBufferMap.erase(event.connectionID.counter);
-}
-
-} // namespace SecurityServer
-
diff --git a/src/server2/service/privilege-by-pid.h b/src/server2/service/privilege-by-pid.h
deleted file mode 100644 (file)
index da5cdde..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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
- */
-/*hcpp
- * @author      Jan Cybulski (j.cybulski@samsung.com)
- * @version     1.0
- * @brief       Implementation of api-check-privilege-by-pid
- */
-
-#ifndef _SECURITY_SERVER_PRIVILEGE_BY_PID_
-#define _SECURITY_SERVER_PRIVILEGE_BY_PID_
-
-#include <service-thread.h>
-#include <generic-socket-manager.h>
-
-#include <message-buffer.h>
-
-namespace SecurityServer {
-
-class PrivilegeByPidService
-  : public SecurityServer::GenericSocketService
-  , public SecurityServer::ServiceThread<PrivilegeByPidService>
-{
-public:
-    typedef std::map<int, MessageBuffer> MessageBufferMap;
-
-    ServiceDescriptionVector GetServiceDescription();
-
-    DECLARE_THREAD_EVENT(AcceptEvent, accept)
-    DECLARE_THREAD_EVENT(WriteEvent, write)
-    DECLARE_THREAD_EVENT(ReadEvent, process)
-    DECLARE_THREAD_EVENT(CloseEvent, close)
-
-    void accept(const AcceptEvent &event);
-    void write(const WriteEvent &event);
-    void process(const ReadEvent &event);
-    void close(const CloseEvent &event);
-private:
-    bool processOne(const ConnectionID &conn, MessageBuffer &buffer);
-
-    MessageBufferMap m_messageBufferMap;
-};
-
-} // namespace SecurityServer
-
-#endif // _SECURITY_SERVER_DATA_SHARE_
diff --git a/src/util/security-server-util-common.c b/src/util/security-server-util-common.c
deleted file mode 100644 (file)
index 7d90d7f..0000000
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- *  security-server
- *
- *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
- *
- *  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
- *
- */
-
-
-#include <poll.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/smack.h>
-#include <fcntl.h>
-#include <sys/un.h>
-#include <errno.h>
-#include <unistd.h>
-#include <stdint.h>
-
-#include <smack-check.h>
-
-#include "security-server-common.h"
-#include "security-server-comm.h"
-#include "security-server-util.h"
-#include "security-server.h"
-
-
-int util_smack_label_is_valid(const char *smack_label)
-{
-    int i;
-
-    if (!smack_label || smack_label[0] == '\0' || smack_label[0] == '-')
-        goto err;
-
-    for (i = 0; smack_label[i]; ++i) {
-        if (i >= SMACK_LABEL_LEN)
-            return 0;
-        switch (smack_label[i]) {
-            case '~':
-            case ' ':
-            case '/':
-            case '"':
-            case '\\':
-            case '\'':
-                goto err;
-            default:
-                break;
-        }
-    }
-
-    return 1;
-err:
-    SEC_SVR_ERR("ERROR: Invalid Smack label: %s", smack_label);
-    return 0;
-}
-
-char *read_exe_path_from_proc(pid_t pid)
-{
-    char link[32];
-    char *exe = NULL;
-    size_t size = 64;
-    ssize_t cnt = 0;
-
-    // get link to executable
-    snprintf(link, sizeof(link), "/proc/%d/exe", pid);
-
-    for (;;)
-    {
-        exe = malloc(size);
-        if (exe == NULL)
-        {
-            SEC_SVR_ERR("Out of memory");
-            return NULL;
-        }
-
-        // read link target
-        cnt = readlink(link, exe, size);
-
-        // error
-        if (cnt < 0 || (size_t) cnt > size)
-        {
-            SEC_SVR_ERR("Can't locate process binary for pid[%d]", pid);
-            free(exe);
-            return NULL;
-        }
-
-        // read less than requested
-        if ((size_t) cnt < size)
-            break;
-
-        // read exactly the number of bytes requested
-        free(exe);
-        if (size > (SIZE_MAX >> 1))
-        {
-            SEC_SVR_ERR("Exe path too long (more than %d characters)", size);
-            return NULL;
-        }
-        size <<= 1;
-    }
-    // readlink does not append null byte to buffer.
-    exe[cnt] = '\0';
-    return exe;
-}
-
-/*
- * Function that checks if API caller have access to specified label.
- * In positive case (caller has access to the API) returns 1.
- * In case of no access returns 0, and -1 in case of error.
- */
-int authorize_SS_API_caller_socket(int sockfd, char *required_API_label, char *required_rule)
-{
-    int retval;
-    int checkval;
-    char *label = NULL;
-//    char *path = NULL;
-    //for getting socket options
-    struct ucred cr;
-    unsigned int len;
-
-    SEC_SVR_DBG("Checking client SMACK access to SS API");
-
-    if (!smack_check()) {
-        SEC_SVR_ERR("No SMACK on device found, API PROTECTION DISABLED!!!");
-        retval = 1;
-        goto end;
-    }
-
-    retval = smack_new_label_from_socket(sockfd, &label);
-    if (retval < 0) {
-        SEC_SVR_ERR("%s", "Error in getting label from socket");
-        retval = -1;
-        goto end;
-    }
-
-    retval = smack_have_access(label, required_API_label, required_rule);
-
-    len = sizeof(cr);
-    checkval = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
-
-    if (checkval < 0) {
-        SEC_SVR_ERR("Error in getsockopt(): client pid is unknown.");
-//        if (retval) {
-//            SEC_SVR_DBG("SS_SMACK: subject=%s, object=%s, access=%s, result=%d", label, required_API_label, required_rule, retval);
-//        } else {
-//            SEC_SVR_ERR("SS_SMACK: subject=%s, object=%s, access=%s, result=%d", label, required_API_label, required_rule, retval);
-//        }
-    } else {
-//        path = read_exe_path_from_proc(cr.pid);
-
-        if (retval == 0) {
-            retval = smack_pid_have_access(cr.pid, required_API_label, required_rule);
-        }
-
-        const char *cap_info = "";
-        if (retval == 0)
-            cap_info = ", no CAP_MAC_OVERRIDE";
-
-//        if (retval > 0) {
-//            SEC_SVR_DBG("SS_SMACK: caller_pid=%d, subject=%s, object=%s, access=%s, result=%d, caller_path=%s",
-//                        cr.pid, label, required_API_label, required_rule, retval, path);
-//        } else {
-//            SEC_SVR_ERR("SS_SMACK: caller_pid=%d, subject=%s, object=%s, access=%s, result=%d, caller_path=%s%s",
-//                        cr.pid, label, required_API_label, required_rule, retval, path, cap_info);
-//        }
-    }
-
-end:
-//    if (path != NULL)
-//        free(path);
-    if (label != NULL)
-        free(label);
-
-    return retval;
-}
diff --git a/src/util/smack-check.c b/src/util/smack-check.c
deleted file mode 100644 (file)
index 946d7aa..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-#include <sys/smack.h>
-
-#include <security-server-common.h>
-#include <smack-check.h>
-
-int smack_runtime_check(void)
-{
-    static int smack_present = -1;
-    if (-1 == smack_present) {
-        if (NULL == smack_smackfs_path()) {
-            SECURE_SLOGD("%s","security-server: no smack found on device");
-            smack_present = 0;
-        } else {
-            SECURE_SLOGD("%s","security-server: found smack on device");
-            smack_present = 1;
-        }
-    }
-    return smack_present;
-}
-
-int smack_check(void)
-{
-#ifndef SMACK_ENABLED
-    return 0;
-#else
-    return smack_runtime_check();
-#endif
-}