2 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
17 * @file socket-2-id.cpp
18 * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
21 #include <sys/smack.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
25 #include <dpl/log/log.h>
26 #include <protocols.h>
27 #include <socket-2-id.h>
33 int assignToString(std::vector<char> &vec, socklen_t len, std::string &res) {
34 if (vec.size() <= len)
37 vec[len] = 0; // old implementation getsockopt returns cstring without 0
38 if (vec[len-1] == 0) {
39 --len; // new implementation of getsockopt returns cstring size+1
42 res.assign(vec.data(), len);
46 } // namespace anonymous
48 int Socket2Id::getCredentialsFromSocket(int sock, std::string &res) {
49 std::vector<char> result(SMACK_LABEL_LEN+1);
50 socklen_t length = SMACK_LABEL_LEN;
52 if (0 == getsockopt(sock, SOL_SOCKET, SO_PEERSEC, result.data(), &length)) {
53 return assignToString(result, length, res);
56 if (errno != ERANGE) {
57 LogError("getsockopt failed");
61 result.resize(length+1);
63 if (0 > getsockopt(sock, SOL_SOCKET, SO_PEERSEC, result.data(), &length)) {
64 LogError("getsockopt failed with errno: " << errno);
68 return assignToString(result, length, res);
71 void Socket2Id::resetCache() {