summaryrefslogtreecommitdiff
path: root/src/manager/client/client-common.cpp
blob: 9ca3df9e48793dc67cd9cc63cf4cbeab22842e32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*
 *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 */
/*
 * @file        client-common.cpp
 * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
 * @author      Zofia Abramowska (z.abramowska@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/errno_string.h>
#include <dpl/log/log.h>
#include <dpl/serialization.h>
#include <dpl/singleton.h>

#include <message-buffer.h>
#include <log-setup.h>

#include <ckm/ckm-error.h>
#include <ckmc/ckmc-type.h>
#include <client-common.h>
#include <ckmc-type-converter.h>

namespace {

const int POLL_TIMEOUT = 600000;

} // namespace anonymous

namespace CKM {

SockRAII::SockRAII() : m_sock(-1) {}

SockRAII::~SockRAII()
{
	disconnect();
}

int SockRAII::connect(const char *interface)
{
	if (!interface) {
		LogError("No valid interface address given.");
		return CKM_API_ERROR_INPUT_PARAM;
	}

	int localSock = socket(AF_UNIX, SOCK_STREAM, 0);

	if (localSock < 0) {
		LogError("Error creating socket: " << CKM::GetErrnoString(errno));
		return CKM_API_ERROR_SOCKET;
	}

	int retCode = connectWrapper(localSock, interface);

	if (retCode != CKM_API_SUCCESS) {
		close(localSock);
		return retCode;
	}

	disconnect();

	m_sock = localSock;

	return CKM_API_SUCCESS;
}

int SockRAII::connectWrapper(int sock, const char *interface)
{
	int flags;

	// we need to be sure that socket is in blocking mode
	if ((flags = fcntl(sock, F_GETFL, 0)) < 0 ||
			fcntl(sock, F_SETFL, flags & ~O_NONBLOCK) < 0) {
		LogError("Error in fcntl: " << CKM::GetErrnoString(errno));
		return CKM_API_ERROR_SOCKET;
	}

	sockaddr_un clientAddr;
	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 CKM_API_ERROR_INPUT_PARAM;
	}

	strncpy(clientAddr.sun_path, interface, sizeof(clientAddr.sun_path) - 1);
	LogDebug("ClientAddr.sun_path = " << interface);

	int retval = TEMP_FAILURE_RETRY(::connect(sock, (struct sockaddr *)&clientAddr,
									SUN_LEN(&clientAddr)));

	// we don't need to support EINPROGRESS because the socket is in blocking mode
	if (-1 == retval) {
		if (errno == EACCES) {
			LogError("Access denied to interface: " << interface);
			return CKM_API_ERROR_ACCESS_DENIED;
		}

		LogError("Error connecting socket: " << CKM::GetErrnoString(errno));
		return CKM_API_ERROR_SOCKET;
	}

	// make the socket non-blocking
	if ((flags = fcntl(sock, F_GETFL, 0)) < 0 ||
			fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
		LogError("Error in fcntl: " << CKM::GetErrnoString(errno));
		return CKM_API_ERROR_SOCKET;
	}

	return CKM_API_SUCCESS;
}

bool SockRAII::isConnected() const
{
	return (m_sock > -1);
}

void SockRAII::disconnect()
{
	if (isConnected())
		close(m_sock);

	m_sock = -1;
}

int SockRAII::waitForSocket(int event, int timeout)
{
	int retval;
	pollfd desc[1];
	desc[0].fd = m_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)
		LogError("Error in poll: " << CKM::GetErrnoString(errno));

	return retval;
}

int SockRAII::get() const
{
	return m_sock;
}

AliasSupport::AliasSupport(const Alias &alias)
{
	std::size_t separator_pos = alias.rfind(CKM::LABEL_NAME_SEPARATOR);

	if (separator_pos == Alias::npos) {
		m_label.clear();
		m_name = alias;
	} else {
		m_label = alias.substr(0, separator_pos);
		m_name = alias.substr(separator_pos + strlen(CKM::LABEL_NAME_SEPARATOR));
	}
}

Alias AliasSupport::merge(const Label &label, const Name &name)
{
	if (label.empty())
		return name;

	std::stringstream output;
	output << label << std::string(CKM::LABEL_NAME_SEPARATOR) << name;
	return output.str();
}

const Name &AliasSupport::getName() const
{
	return m_name;
}

const Label &AliasSupport::getLabel() const
{
	return m_label;
}

bool AliasSupport::isLabelEmpty() const
{
	return m_label.empty();
}

ServiceConnection::ServiceConnection(const char *service_interface)
{
	if (service_interface)
		m_serviceInterface = std::string(service_interface);
}

int ServiceConnection::processRequest(
	const CKM::RawBuffer &send_buf,
	CKM::MessageBuffer &recv_buf)
{
	int ec;

	if (CKM_API_SUCCESS != (ec = send(send_buf)))
		return ec;

	return receive(recv_buf);
}

int ServiceConnection::prepareConnection()
{
	if (m_socket.isConnected())
		return CKM_API_SUCCESS;

	return m_socket.connect(m_serviceInterface.c_str());
}

int ServiceConnection::send(const CKM::RawBuffer &send_buf)
{
	int retCode = prepareConnection();

	if (retCode != CKM_API_SUCCESS) {
		LogError("Failed to prepare connection: " << retCode);
		return retCode;
	}

	ssize_t done = 0;

	while ((send_buf.size() - done) > 0) {
		if (0 >= m_socket.waitForSocket(POLLOUT, POLL_TIMEOUT)) {
			LogError("Error in WaitForSocket.");
			retCode = CKM_API_ERROR_SOCKET;
			break;
		}

		ssize_t temp = TEMP_FAILURE_RETRY(::send(m_socket.get(),
										  &send_buf[done],
										  send_buf.size() - done,
										  MSG_NOSIGNAL));

		if (-1 == temp) {
			LogError("Error in write: " << CKM::GetErrnoString(errno));
			retCode = CKM_API_ERROR_SOCKET;
			break;
		}

		done += temp;
	}

	if (retCode != CKM_API_SUCCESS)
		m_socket.disconnect();

	return retCode;
}

int ServiceConnection::receive(CKM::MessageBuffer &recv_buf)
{
	if (!m_socket.isConnected()) {
		LogError("Not connected!");
		return CKM_API_ERROR_SOCKET;
	}

	int ec = CKM_API_SUCCESS;
	const size_t c_recv_buf_len = 2048;
	char buffer[c_recv_buf_len];

	do {
		if (0 >= m_socket.waitForSocket(POLLIN, POLL_TIMEOUT)) {
			LogError("Error in WaitForSocket.");
			ec = CKM_API_ERROR_SOCKET;
			break;
		}

		ssize_t temp = TEMP_FAILURE_RETRY(::recv(m_socket.get(),
										  buffer,
										  sizeof(buffer),
										  0));

		if (-1 == temp) {
			LogError("Error in read: " << CKM::GetErrnoString(errno));
			ec = CKM_API_ERROR_SOCKET;
			break;
		}

		if (0 == temp) {
			LogError("Read return 0/Connection closed by server(?)");
			ec = CKM_API_ERROR_SOCKET;
			break;
		}

		CKM::RawBuffer raw(buffer, buffer + temp);
		recv_buf.Push(raw);
	} while (!recv_buf.Ready());

	if (ec != CKM_API_SUCCESS)
		m_socket.disconnect();

	return ec;
}

ServiceConnection::~ServiceConnection()
{
}

int try_catch(const std::function<int()> &func)
{
	int retval = CKM_API_ERROR_UNKNOWN;

	try {
		return func();
	} catch (const MessageBuffer::Exception::Base &e) {
		LogError("CKM::MessageBuffer::Exception " << e.DumpToString());
	} catch (const std::exception &e) {
		LogError("STD exception " << e.what());
	} catch (...) {
		LogError("Unknown exception occured");
	}

	return retval;
}

int try_catch_enclosure(const std::function<int()> &func)
{
	try {
		return func();
	} catch (const Exc::Exception &e) {
		return to_ckmc_error(e.error());
	} catch (const std::bad_alloc &e) {
		LogError("memory allocation exception: " << e.what());
		return CKMC_ERROR_OUT_OF_MEMORY;
	} catch (const std::exception &e) {
		LogError("std exception occured: " << e.what());
		return CKMC_ERROR_UNKNOWN;
	} catch (...) {
		LogError("Unknown exception occured.");
		return CKMC_ERROR_UNKNOWN;
	}
}

void try_catch_async(const std::function<void()> &func,
					 const std::function<void(int)> &error)
{
	try {
		func();
	} catch (const MessageBuffer::Exception::Base &e) {
		LogError("CKM::MessageBuffer::Exception " << e.DumpToString());
		error(CKM_API_ERROR_BAD_REQUEST);
	} catch (const Exc::Exception &e) {
		LogError("Exception: " << e.what());
		error(e.error());
	} catch (const std::exception &e) {
		LogError("STD exception " << e.what());
		error(CKM_API_ERROR_UNKNOWN);
	} catch (...) {
		LogError("Unknown exception occured");
		error(CKM_API_ERROR_UNKNOWN);
	}
}

} // namespace CKM

static void init_lib(void) __attribute__((constructor));
static void init_lib(void)
{
	CKM::SetupClientLogSystem();
}

static void fini_lib(void) __attribute__((destructor));
static void fini_lib(void)
{
}