4c33102b8b2bedfe925df0b39bb5473bcae9e435
[framework/security/security-server.git] / socket_connection / client / SecuritySocketClient.cpp
1 /*
2  * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /**
17  * @file        SecuritySocketClient.cpp
18  * @author      Zofia Abramowska (z.abramowska@samsung.com)
19  * @version     1.0
20  * @brief       Implemtation of socket client class.
21  */
22
23 #include <sys/socket.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <sys/types.h>
27 #include <sys/un.h>
28 #include <errno.h>
29
30 #include "SecuritySocketClient.h"
31 #include "security_daemon_socket_config.h"
32
33 void SecuritySocketClient::throwWithErrnoMessage(const std::string& specificInfo){
34     LogError(specificInfo << " : " << strerror(errno));
35     ThrowMsg(Exception::SecuritySocketClientException, specificInfo << " : " << strerror(errno));
36 }
37
38 SecuritySocketClient::SecuritySocketClient(const std::string& interfaceName) {
39     m_interfaceName = interfaceName;
40     m_serverAddress = WrtSecurity::SecurityDaemonSocketConfig::SERVER_ADDRESS();
41     LogInfo("Client created");
42 }
43
44 void SecuritySocketClient::connect(){
45     struct sockaddr_un remote;
46     if(-1 == (m_socketFd = socket(AF_UNIX, SOCK_STREAM,0))){
47         throwWithErrnoMessage("socket()");
48     }
49
50     //socket needs to be nonblocking, because read can block after select
51     int flags;
52     if (-1 == (flags = fcntl(m_socketFd, F_GETFL, 0)))
53         flags = 0;
54     if(-1 == (fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK))){
55         throwWithErrnoMessage("fcntl");
56     }
57
58     bzero(&remote, sizeof(remote));
59     remote.sun_family = AF_UNIX;
60     strcpy(remote.sun_path, m_serverAddress.c_str());
61     if(-1 == ::connect(m_socketFd, (struct sockaddr *)&remote, SUN_LEN(&remote))){
62         throwWithErrnoMessage("connect()");
63     }
64
65     m_socketConnector.reset(new SocketConnection(m_socketFd));
66
67     LogInfo("Client connected");
68 }
69
70 void SecuritySocketClient::disconnect(){
71     //Socket should be already closed by server side, 
72     //even though we should close it in case of any errors
73     close(m_socketFd);
74     LogInfo("Client disconnected");
75 }